如何模拟模块导出功能

问题描述 投票:1回答:1

我有一个这样导出的功能:

// myFunc.js
....
....
module.exports = myFunc;

然后在另一个文件中,我有:

// main.js
const myFunc = require('../../myFunc');
...
...
myFunc.then( .... )

如何使用其他功能在myFunc中模拟myFunc.js?我已经尝试过:

sinon.stub(myFuncFilePath).callsFake(myOtherFuncFilePath);

但是它不起作用,显然是因为myFunc的导出方式。我无法更改在myFunc.js中的导出方式,那么我还能如何模拟它?

javascript testing mocking sinon
1个回答
0
投票

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

© www.soinside.com 2019 - 2024. All rights reserved.