我有一个类modules/handler.js,如下所示:
const {getCompany} = require('./helper');
module.exports = class Handler {
constructor () {...}
async init(){
await getCompany(){
...
}
}它从文件getCompany导入函数modules/helper.js。
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返回一个直接返回对象的函数,但是,这也不起作用。
我会非常感谢每一个指针。谢谢。
发布于 2021-10-29 02:52:44
您所使用的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 |
------------|---------|----------|---------|---------|-------------------https://stackoverflow.com/questions/69759888
复制相似问题