我正在尝试调用一个函数,该函数在我从单元测试中调用的另一个函数中作为函数独立导入。在这种情况下,我如何在函数IWantToSpy上获得1的调用计数?
auditEvent.js:
const { verify } = require('@mycompany/verifylib');
const { functionIWantToSpy } = require('@mycompany/another-lib');
const auditEvent = () => {
verify();
functionIWantToSpy();
};
module.exports = { auditEvent };
测试:
const { verify } = require('@mycompany/verify-lib');
const { functionIWantToSpy } = require('@mycompany/another-lib');
describe('mytest', () => {
let spiedFuntion;
let verifyStub;
beforeEach(() => {
verifyStub = sinon.stub();
({auditEvent} = proxyquire('./auditEvent', {
'@mycompny/verify-lib': {
verify: verifyStub,
'@noCallThru': true,
},
}));
spiedFunction = sinon.spy(functionIWantToSpy);
});
it('should work'), async () => {
auditEvent();
expect(functionIWantToSpy).to.have.callCount(1); // Getting callcount of 0 here...
});
});
间谍活动包括用新函数替换函数。您正在替换标识符functionIWantToSpy
所引用的内容,以便它引用新的间谍函数,而不是require('@mycompany/another-lib').functionIWantToSpy
所引用的原始函数。模块内的代码看不到您的新间谍功能。表达式require('@mycompany/another-lib').functionIWantToSpy
表示原始函数,未更改。
由于require
缓存结果(即,只有第一个require("foo")
执行foo
,任何后续的require("foo")
调用第一个require
调用返回的同一对象(,因此可以使用sinon.spy
:的双参数形式修改require('@mycompany/another-lib')
对象的functionIWantToSpy
方法
spiedFunction = sinon.spy(require('@mycompany/another-lib'), "functionIWantToSpy");
在被测试的模块访问(和存储值(属性之前,您必须执行此操作:
verifyStub = sinon.stub();
// IMPORANT: FIRST, spy the functionIWantToSpy property on the required object before importing auditEvent
spiedFunction = sinon.spy(require('@mycompany/another-lib'), "functionIWantToSpy");
({auditEvent} = proxyquire('./auditEvent', {
'@mycompny/verify-lib': {
verify: verifyStub,
'@noCallThru': true,
},
}));
这应该起作用,因为当auditEvent模块第一次运行并到达时
const { functionIWantToSpy } = require('@mycompany/another-lib');
则CCD_ 12将参考间谍功能。