我有两个功能funcA
和funcB
funcA是一个npm模块,而funcB是调用funcA的自定义函数
funcB.js
const a = require('a')
const funcB = ()=> a.funcA({arg})
我想测试调用funcB时是否已调用a.funcA
funcB.test.js
describe('',()=>{
it('should call a.funcA',()=>{
sandbox.stub(a,'funcA')
funcB()
expect(a.funcA).to.have.been.called;
}
})
funcA
const funcA() {
//....
return func c (){
//other logic here.
}
}
我进行测试时,收到以下消息:我发现a.funcA不是间谍,也不是间谍!错误
我如何对funcA存根?有任何想法吗?香港专业教育学院试图嘲笑,但不会工作。
这里是单元测试解决方案:
funcB.js
:
const a = require("./a");
const funcB = () => a.funcA({ arg: 123 });
exports.funcB = funcB;
a.js
:
exports.funcA = function funcA(args) {
return function c() {};
};
funcB.test.js
:
const { expect } = require("chai");
const sinon = require("sinon");
const a = require("./a");
const { funcB } = require("./funcB");
describe("57796168", () => {
let sandbox;
before(() => {
sandbox = sinon.createSandbox();
});
it("should call a.funcA", () => {
const funcAStub = sandbox.stub(a, "funcA");
funcB();
sinon.assert.calledWith(funcAStub, { arg: 123 });
expect(funcAStub.callCount).to.be.equal(1);
expect(funcAStub.calledWith({ arg: 123 })).to.be.true;
});
});
带有覆盖率报告的单元测试结果:
57796168
✓ should call a.funcA
1 passing (10ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 94.74 | 100 | 66.67 | 94.44 | |
a.js | 50 | 100 | 0 | 50 | 2 |
funcB.js | 100 | 100 | 100 | 100 | |
funcB.test.js | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57796168