Proxyquire不覆盖导出的函数



我有一个类modules/handler.js,它看起来像这样:

const {getCompany} = require('./helper');
module.exports = class Handler {
constructor () {...}
async init(){
await getCompany(){
...
}
}

从文件modules/helper.js中导入函数getCompany:

exports.getCompany = async () => {
// async calls
}

现在在集成测试中,我想存根getCompany方法,它应该只返回一个mockCompany。然而,proxyquire并没有存根getCompany方法,而是调用了真正的方法。测试:

const sinon = require('sinon');
const proxyquire = require("proxyquire");
const Handler = require('../modules/handler');
describe('...', () => {
const getCompanyStub = sinon.stub();
getCompanyStub.resolves({...});
const test = proxyquire('../modules/handler.js'), {
getCompany: getCompanyStub
});
it('...', async () => {
const handler = new Handler();
await handler.init(); // <- calls real method 
... 
});
});

我也试过没有sinon.stub, proxyquire返回一个函数直接返回一个对象,但是,这也没有工作。

我将非常感谢每一个指针。谢谢。

您正在使用的Handler类是require函数所需要的,而不是proxyquire

handler.js:

const { getCompany } = require('./helper');
module.exports = class Handler {
async init() {
await getCompany();
}
};

helper.js:

exports.getCompany = async () => {
// async calls
};

handler.test.js:

const sinon = require('sinon');
const proxyquire = require('proxyquire');
describe('69759888', () => {
it('should pass', async () => {
const getCompanyStub = sinon.stub().resolves({});
const Handler = proxyquire('./handler', {
'./helper': {
getCompany: getCompanyStub,
},
});
const handler = new Handler();
await handler.init();
});
});

测试结果:

69759888
✓ should pass (2478ms)

1 passing (2s)
------------|---------|----------|---------|---------|-------------------
File        | % Stmts | % Branch | % Funcs | % Lines | Uncovered Line #s 
------------|---------|----------|---------|---------|-------------------
All files   |     100 |      100 |     100 |     100 |                   
handler.js |     100 |      100 |     100 |     100 |                   
helper.js  |     100 |      100 |     100 |     100 |                   
------------|---------|----------|---------|---------|-------------------

最新更新