这是我的代码:
// SUT.spec.js
import * as myModule from './myModule';
describe('my issue', () => {
let myFuncSpy = sinon.spy(myModule, 'myFunc');
beforeEach(() => {
myFuncSpy.reset();
});
it('my case A', () => {
SUT.methodA();
expect(myFuncSpy.callCount).to.equal(1); // fails, it says it's 0
});
it('my case B', () => {
SUT.methodB();
expect(myFuncSpy.callCount).to.equal(1); // passes
});
});
在我的模块中,两个方法都调用myFunc
,但是只在methodA
上它没有被注册:
// SUT.js
import { myFunc } from './myModule';
export function methodA() {
myFunc(....);
console.log(myFunc.callCount); // Mocha output shows 1
};
export function methodB() {
myFunc(....);
console.log('method B ran'); // Mocha output shows this line
console.log(myFunc.callCount); // Mocha output shows 1
};
基本上,调用间谍的方式没有明显差异。我很困惑,因为可能会出错。
我在SUT中添加了console.log
语句,以确保间谍正确设置(否则它将没有一个名为callCount
的属性)。另外,如果我注释掉.reset()
调用,则日志语句显示undefined
而不是1
或其他数字。
这可能有什么不对?这当然是实际SUT的简化版本。但是,console.log
语句表明问题绝对不是线路没有被执行。
在断言之前,您必须等待异步方法。