问题描述
我正在尝试使用用 Sinon 编写的测试用例跟踪对另一个函数的调用次数。我有以下代码,在运行测试时,calledFuncSpy
callCount 总是让我得到 0,这是意料之外的。同时,在 console.log
上运行另一个间谍给了我正确的输出,我在代码中留下了注释。有谁知道可能是什么问题?
specs/mymodule.js
const mymodule = require("../src/mymodule.js");
var sinon = require("sinon");
const assert = require("assert");
describe("Test suite",function() {
let calledFuncSpy;
let consoleSpy;
beforeEach(function () {
calledFuncSpy = sinon.spy(mymodule,"calledFunc");
consoleSpy = sinon.spy(console,"log");
})
afterEach(function () {
calledFuncSpy.restore();
consoleSpy.restore();
})
it("Test the add method",function () {
mymodule.ownHelloWorld();
assert.deepStrictEqual(calledFuncSpy.callCount,1);
// assert.deepStrictEqual(consoleSpy.callCount,1);
});
})
src/mymodule.js
function ownHelloWorld() {
calledFunc();
}
function calledFunc() {
console.log("Hello world");
}
module.exports = {
ownHelloWorld,calledFunc
}
解决方法
在
calledFunc
函数内调用的 ownHelloWorld
不能被存根。它将始终使用原始的 calledFunc
函数。 sinon.spy(mymodule,"calledFunc")
在调用 ownHelloWorld
函数时不能修改它的引用。另外,请参阅此 comment
你可以像这样重构它:
mymodule.js
:
function ownHelloWorld() {
module.exports.calledFunc();
}
function calledFunc() {
console.log('Hello world');
}
module.exports = {
ownHelloWorld,calledFunc,};
mymodule.test.js
:
const mymodule = require('./mymodule');
var sinon = require('sinon');
describe('Test suite',function () {
let calledFuncSpy;
let consoleSpy;
beforeEach(function () {
calledFuncSpy = sinon.spy(mymodule,'calledFunc');
consoleSpy = sinon.spy(console,'log');
});
afterEach(function () {
calledFuncSpy.restore();
consoleSpy.restore();
});
it('Test the add method',function () {
mymodule.ownHelloWorld();
sinon.assert.calledOnce(calledFuncSpy);
});
});
测试结果:
Test suite
Hello world
✓ Test the add method
1 passing (5ms)
-------------|---------|----------|---------|---------|-------------------
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s
-------------|---------|----------|---------|---------|-------------------
All files | 100 | 100 | 100 | 100 |
mymodule.js | 100 | 100 | 100 | 100 |
-------------|---------|----------|---------|---------|-------------------