不幸的是,你不能用现有的代码来测试它们。这些函数是包装函数作用域的私有函数(不能在其外部访问)。但是,您可以重新组织代码以允许这种情况发生:
// module 1
function initSomethings($) { // <-- notice I added a name
function iWantToTestThisOne_1() {
//do something
doSomething();
}
function iWantToTestThisOne_2() {
//do something
doSomething();
}
function iWantToTestThisOne_3() {
//do something
doSomething();
}
function doSomething() {
//doing something
}
return { // give back the methods in here...
iWantToTestThisOne_1,
iWantToTestThisOne_2,
iWantToTestThisOne_3,
doSomething
// Note that we don't have to return ALL of them, so you could keep some of them private by not returning them here
};
}; // <-- notice that I am NOT calling the wrapper function
然后,在一些“主”模块中,我们可以初始化我们的函数:
// "main" module
initSomething();
initAnother();
QUnit.test('iWantToTestThisOne_1()', function(assert){
// Start by initializing your functions...
let methods = initSomething();
// Then stub it out...
let stub_doSomething = sinon.stub(methods, "doSomething").returns("something");
// Now you call the function you're testing:
methods.iWantToTestThisOne_1();
// And do your assertions
assert.equal(stub_doSomething.called, true, "doSomething() is called");
// more assertions...
});