[英]How to mock a module export function
I have a function that is exported like this:我有一个这样导出的函数:
// myFunc.js
....
....
module.exports = myFunc;
And then in another file I have:然后在另一个文件中我有:
// main.js
const myFunc = require('../../myFunc');
...
...
myFunc.then( .... )
How can I mock myFunc
in myFunc.js
with another function?如何使用另一个函数在
myFunc.js
模拟myFunc
? I've tried:我试过了:
sinon.stub(myFuncFilePath).callsFake(myOtherFuncFilePath);
But it's not working, apparently because of the way myFunc
is exported.但它不起作用,显然是因为
myFunc
的导出方式。 I can't change the way it is exported in myFunc.js
, so how else can I mock it?我无法更改它在
myFunc.js
导出方式,那么我还能如何模拟它呢?
sinon doesn't support stub a function directly. sinon 不直接支持存根函数。 You need use proxyquire to rewire the module:
您需要使用proxyquire重新连接模块:
Eg myFunc.js
:例如
myFunc.js
:
async function myFunc() {
console.log('myFunc');
}
module.exports = myFunc;
main.js
: main.js
:
const myFunc = require('./myFunc');
function main() {
return myFunc().then(res => console.log(res));
}
module.exports = main;
main.spec.js
: 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;
});
});
Unit test result with coverage report:带有覆盖率报告的单元测试结果:
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 |
--------------|----------|----------|----------|----------|-------------------|
Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57013728源代码: https : //github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/57013728
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.