【发布时间】:2018-12-08 14:18:12
【问题描述】:
我的测试功能如下:
const testLibrary = require("./test");
describe("Top Test", function() {
it("should test function", function(done) {
testLibrary.print();
done();
});
});
test.ts 有以下两个功能:
export function stubMe() {
console.log("original function");
}
export function print() {
stubMe();
}
当我运行测试时,它会打印:'original function'
我现在尝试按如下方式存根测试:
const testLibrary = require("./test");
const sinon = require("sinon");
const stubMe = sinon.stub(testLibrary, "stubMe");
stubMe.yields();
describe("Top Test", function() {
it("should test function", function(done) {
testLibrary.print();
done();
});
});
我的测试函数仍然打印“原始函数”,表明该函数没有被存根。
如何存根 stubMe 函数?
更新:
我已经根据下面 Ankit 的解决方案修改了我的代码:
const sinon = require("sinon");
const testLibrary = require("./test");
testLibrary.stubMe();
const stubMe = new sinon.stub(testLibrary, "stubMe").callsFake(function () {
console.log("console from stub");
});
testLibrary.stubMe();
describe("Top Test", function () {
it("should test function", function (done) {
testLibrary.print();
done();
});
});
奇怪的是,打印出来的是:
original function
console from stub
Top Test
original function
为什么存根会在测试期间恢复?
【问题讨论】:
-
因为在一种情况下您调用
testLibrary.stubMe(),而在另一种情况下您调用stubMe()。这就是答案所说的。
标签: node.js typescript mocha.js sinon