[英]How can I stub the following function in sinon?
我的測試功能如下:
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();
}
當我運行測試時,它會打印:'原始功能'
我現在嘗試按以下方式對測試進行存根:
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
為什么存根在測試期間會還原?
使用callsFake()
而不是yields()
例如:
const testLibrary = require('./test');
const sinon = require('sinon');
const stubMe = new sinon.stub(testLibrary, 'stubMe');
stubMe.callsFake(function () {
console.log('console from stub');
});
describe('Top Test', function () {
it('should test function', function (done) {
testLibrary.print();
done();
});
});
無法監視或模擬該函數。 stubMe
在同一模塊中直接引用。
如相關的Jest問題中所述,提高可測試性的一種方法是將函數移至不同的模塊:
// one module
export function stubMe() {
console.log("original function");
}
// another module
import { stubMe } from '...';
export function print() {
stubMe();
}
在這種情況下,可以窺探或嘲笑testLibrary.stubMe
,但僅當使用非本機ES模塊時才可以,因為ES模塊導出在本機實現中是只讀的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.