所以基本上我有我想要測試,我們將調用函數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
}