[英]Sinon spy function called but not tracked
我正在使用Mocha和sinon監視函數調用。 該函數被正確調用,但間諜沒有跟蹤它。
這是我正在測試的模塊
export default (() => {
function test1(){
console.log('called second func');
return 5;
}
function callThis(){
console.log('called first func');
test1();
}
return {
test1,
callThis
};
})();
這是測試
import Common from './common';
describe('spy test', () => {
var setSpy = sinon.spy(Common, 'test1');
Common.callThis();
var result = setSpy.called;
it(`does the test`, () => {
expect(result).to.equal(true);
});
});
我基本上調用第一個函數,但想檢查第二個函數被調用作為結果。 控制台日志告訴我這種情況正在發生,但間諜返回false並且沒有注意到它正在監視的事情。 我錯過了什么嗎?
當你調用sinon.spy(Common, 'test1');
您正在修改Common
對象上的test1
字段以將其替換為間諜。 但是, common.js
的代碼是直接調用test1
而不是通過模塊導出的對象調用test1
。 因此,當您執行Common.callThis()
,不會觸及間諜,並且您會收到您觀察到的錯誤。
這是一個修改后的common.js
文件,允許您的測試通過:
export default (() => {
var obj = {};
obj.test1 = function test1(){
console.log('called second func');
return 5;
}
obj.callThis = function callThis(){
console.log('called first func');
// This calls `test1` through `obj` instead of calling it directly.
obj.test1();
}
return obj;
})();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.