[英]sinon stub or else for function not a method
有沒有辦法將sinon.stub()
僅用於沒有帶有方法的對象的函數,例如,
function getSome(){}
sinon.stub(getSome)
還是有另一種 sinon 方法可以做到這一點?
簡短的回答,sinon 沒有直接存根獨立函數的方法。
Nodejs 會加載和緩存默認的導出函數,因此除非我們在緩存對象中再次重新加載模塊,否則像 sinon 這樣的存根庫將無法偽造/監視它。
這是一個解決方案:
mod.ts
:
module.exports = function getSome() {
console.log("real get some");
};
index.ts
:
const getSome = require("./mod");
module.exports = function main() {
return getSome();
};
index.spec.ts
:
import sinon from "sinon";
import { expect } from "chai";
describe("getSome", () => {
it("should stub", () => {
const getSomeStub = sinon.stub().returns("stub get some");
require.cache[require.resolve("./mod.ts")] = {
exports: getSomeStub,
};
const main = require("./");
const actual = main();
expect(actual).to.be.equal("stub get some");
sinon.assert.calledOnce(getSomeStub);
});
});
100% 覆蓋率的單元測試結果:
getSome
✓ should stub (88ms)
1 passing (93ms)
---------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
---------------|----------|----------|----------|----------|-------------------|
All files | 100 | 100 | 100 | 100 | |
index.spec.ts | 100 | 100 | 100 | 100 | |
index.ts | 100 | 100 | 100 | 100 | |
---------------|----------|----------|----------|----------|-------------------|
源代碼: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59064196
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.