所以基本上我有我想要测试,我们将调用函数A.我想测试,如果函数B被调用函数的内部函数。问题在于函数B在函数A中被解析的Promise异步调用。这将导致sinon断言失败,因为测试将在函数B被调用之前完成!如何测试,如果函数A被调用的测试函数B内,如果它被称为异步
这是一个工作代码场景。
const sinon = require('sinon');
describe('functionToBeTested',() => {
it('someFunction is called',() => {
// spy on the function we need to check if called
const spy = sinon.spy(someClass.prototype, 'someFunction');
// call the function being tested
functionToBeTested();
// check if spy was called
sinon.assert.called(spy);
});
});
class someClass {
someFunction() {
console.log('Hello');
}
}
const somePromise = Promise.resolve();
function functionToBeTested() {
const instance = new someClass();
// some synchronous code here
// if instance.someFunction() is called here the test will pass
// .
// .
// .
somePromise.then(() => {
instance.someFunction();
// the function is called and Hello is printed but the test will fail
})
// .
// .
// .
// some synchronous code here
// if instance.someFunction() is called here the test will pass
}