所以基本上我有我想要测试的函数,我们将调用函数 A。我想测试函数 B 是否在函数 A 内部被调用。问题是函数 B 在函数 A 内部通过已解析的 Promise 异步调用。这将导致 sinon 断言失败,因为测试将在函数 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
}