【发布时间】:2021-12-13 23:57:17
【问题描述】:
我有一个班级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 返回一个函数,直接返回一个对象,但是,这也不起作用。
我会非常感谢每一个指针。 谢谢。
【问题讨论】:
标签: node.js testing mocking sinon proxyquire