我正在尝试测试从另一个具有奇怪导出结构的模块导入的模块。
我正在将javascript与node一起使用,并且开玩笑地进行测试。
这基本上是导出和测试的代码结构。
// weirdModule.js
module.exports = ({param1, param2}) = {
const weirdModuleFunction = async () => {
return await someIrrelevantFunction(param1, param2);
};
return async () => {
try {
return await weirdModuleFunction();
}
catch (e) {
throw e;
}
};
}
}
// testThisModule.js
const _weirdModuleFunction = require('weirdModule.js');
const testThisFunction = () => {
const weirdModuleFunction = _weirdModuleFunction({'abc',123});
let someDataIWantToBeMockedFromWeirdModule = await weirdModuleFunction();
const resultIWantToExpect = someDataIWantToBeMockedFromWeirdModule + ' someDataForExample';
return resultIWantToExpect;
};
module.exports = { testThisFunction }
//testThisModule.test.js
const { testThisFunction } = require('testThisModule.js');
//jest mocks to return different values for weirdModule.js
it('should return some value from weirdModule + someData',()=>{
//mockImplementation for weirdModule, maybe even mockImplementationOnce for successive testing
expect(testThisFunction()).toEqual('whatIexpect1 someDataForExample');
expect(testThisFunction()).toEqual('whatIexpectWithADifferentMockImplementation someDataForExample');
});
我想要一个解决方案,允许我模拟weirdModule.js返回的内容,并且还能够模拟它,以便它返回不同的值。
我有很多针对不同分支的测试,所以我需要能够更改weirdModule的模拟返回值,这样我才能拥有可用于许多测试的数据,其中一些可用于某些特定测试
我不能更改weirdModule的结构(我没有设计它),除了玩笑,我不能使用其他任何东西,也不想使用来自__mocks __
的手动模拟我设法使其仅与一个返回值一起使用,但是我需要能够将其更改为不同的值。当前它是这样的:
jest.mock('weirdModule.js', () => () => {
return jest.fn(() => {
return 'whatIexpect1';
});
}
我该如何实现?数天来,我一直在努力地尝试使玩笑变得更好,并且在为不同的测试模拟不同的值时不抛出“ weirdModuleFunction不是函数”。任何帮助表示赞赏。
答案 0 :(得分:0)
您需要在测试文件中将weirdModule.js
捕获为模拟模块。为此,请将其添加到testThisModule.test.js
const weirdModule = require('weirdModule.js');
jest.mock('weirdModule.js');
现在,您可以根据需要模拟怪异的模块,像这样:
it('should return some value from weirdModule + someData', async () => {
//mockImplementation for weirdModule, maybe even mockImplementationOnce for successive testing
weirdModule.mockImplementationOnce( () => {
return () => {
return 'whatIexpect1';
};
});
expect(await testThisFunction()).toEqual('whatIexpect1 someDataForExample');
weirdModule.mockImplementationOnce( () => {
return () => {
return 'whatIexpectWithADifferentMockImplementation';
};
});
expect(await testThisFunction()).toEqual('whatIexpectWithADifferentMockImplementation someDataForExample');
});
希望这会有所帮助!