[英]How to test if function A was called inside the test function B if it was called asynchronously
因此,基本上我有要測試的函數,我們將其稱為函數A。我想測試函數B是否在函數A內部被調用。問題是通過已解決的Promise在函數A內部異步調用了函數B。 這將導致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
}
您的示例有點不合常規。 您具有具有雙重行為(同時同步和異步)的functionToBeTested 。 在對該方法進行測試時,應事先對其行為進行熟知和標准化,以便可以相應地構造測試和斷言。
在這種情況下的問題是,你嘗試驗證功能的行為是同步模式,雖然內部零件在發射后不管的方式工作-即沒有對instance.someFunction的結果,不存在依賴關系()方法。
如果functionToBeTested()返回了一個promise-因此在設計上是異步的,那么對於您的測試場景而言,這將很簡單。 但是在這種情況下,您還需要一種非常規的測試方法。 這意味着如果您執行以下操作:
describe('functionToBeTested', () => {
it('someFunction is called', (done) => {
// spy on the function we need to check if called
const spy = sinon.spy(SomeClass.prototype, 'someFunction');
// call the function being tested
functionToBeTested();
setTimeout(() => {
// check if spy was called
sinon.assert.called(spy);
done();
}, 10);
});
});
測試會通過。 這里發生的是,我們通過使用回調中的done參數聲明了測試異步 。 另外,我們在檢查間諜是否被調用之前添加了一個計時器來模擬延遲。
由於“即發即忘 ”呼叫僅打印出一條消息,因此等待10毫秒就足夠了。 如果承諾需要較長時間才能完成,則應調整等待時間。
如前所述,非常規實現需要非常規方法。 我建議您重新考慮您的要求並重新設計解決方案。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.