问题
After reading about javascript unit testing / bdd in VS I found that you could use a combination of:
- ReSharper - support for PhantomJS headless + Jasmine/QUnit
- Testr - mock Require dependencies
I used Jasmine in a test script and was able to successfully run some simple tests, with functions declared in the same file.
However, I could not find / build a working end to end example for testing a js module with dependencies. I am trying to build on the example used in the SPA Jumpstart example by John Papa.
So given a people.js viewmodel module that has a dependency in datacontext.js:
define(['services/datacontext'],
function (datacontext) {
var peopleViewModel = {
title: 'People page'
};
return peopleViewModel;
})
Folder Structure:
/App/Viewmodels : people.js
/App/Services : datacontext.js
/App/Tests : peopletests.js
What do I need to add in a peopletests.js to make this test run?
describe("My Tests Set", function () {
it("People Title Test", function () {
expect(peopleViewModel.title()).toEqual("People page");
});
});
回答1:
try this:
- add require.js as a reference path
- add a require.config script as a reference path
- load require modules.
peopletests.js:
/// <reference path="~/Scripts/require.js"/>
/// <reference path="~/App/requireConfig.js"/>
describe("My Tests Set", function () {
var people;
beforeEach(function () {
if (!people) { //if people is undefined it will try to load it
require(["people"], function (peopleViewModel) {
people = peopleViewModel;
});
//waits for people to be defined (loaded)
waitsFor(function () {
return people;
}, "loading external module", 1000);
}
});
it("People Title Test", function () {
expect(people.title).toEqual("People page");
});
});
requireConfig.js:
//beware of the port, if your app is runing in port 8080
//you need to specified that to require since resharper whould use a random port
//when running tests
require.config({
baseUrl: 'http://localhost:8080/App/',
paths: {
people: 'ViewModels/people',
dataContext: 'Services/datacontext'
}
});
people.js
define(['dataContext'],
function (datacontext) {
var peopleViewModel = {
title: 'People page'
};
return peopleViewModel;
})
来源:https://stackoverflow.com/questions/18234707/how-to-test-spa-js-modules-with-resharper-testr-jasmin