[英]How to mock a un-export (private) function inside user module using Jest
[英]How to mock a module export function
我有一個這樣導出的函數:
// myFunc.js
....
....
module.exports = myFunc;
然后在另一個文件中我有:
// main.js
const myFunc = require('../../myFunc');
...
...
myFunc.then( .... )
如何使用另一個函數在myFunc.js
模擬myFunc
? 我試過了:
sinon.stub(myFuncFilePath).callsFake(myOtherFuncFilePath);
但它不起作用,顯然是因為myFunc
的導出方式。 我無法更改它在myFunc.js
導出方式,那么我還能如何模擬它呢?
sinon 不直接支持存根函數。 您需要使用proxyquire重新連接模塊:
例如myFunc.js
:
async function myFunc() {
console.log('myFunc');
}
module.exports = myFunc;
main.js
:
const myFunc = require('./myFunc');
function main() {
return myFunc().then(res => console.log(res));
}
module.exports = main;
main.spec.js
:
const sinon = require('sinon');
const { expect } = require('chai');
const proxyquire = require('proxyquire');
describe('main', () => {
it('should stub myFunc', async () => {
const myFuncStub = sinon.stub().resolves('fake data');
const main = proxyquire('./main', {
'./myFunc.js': myFuncStub
});
const logSpy = sinon.spy(console, 'log');
const actual = await main();
expect(actual).to.be.undefined;
expect(myFuncStub.calledOnce).to.be.true;
expect(logSpy.calledWith('fake data')).to.be.true;
});
});
帶有覆蓋率報告的單元測試結果:
main
fake data
✓ should stub myFunc (44ms)
1 passing (49ms)
--------------|----------|----------|----------|----------|-------------------|
File | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files | 94.44 | 100 | 80 | 94.12 | |
main.js | 100 | 100 | 100 | 100 | |
main.spec.js | 100 | 100 | 100 | 100 | |
myFunc.js | 50 | 100 | 0 | 50 | 2 |
--------------|----------|----------|----------|----------|-------------------|
源代碼: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57013728
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.