[英]jest.doMock and JSON import mocking
I have such code to test:我有这样的代码要测试:
...
import data from '../data/mock.json';
// function is async
export const something = async () => {
try {
...
if (!data) {
throw 'error is here!';
}
return data;
} catch (error) {
return error;
}
};
and my spec looks so:我的规格看起来是这样的:
...
import { something } from './handler';
describe('handler: something', () => {
beforeEach(() => {
jest.resetModules();
});
describe('on something', () => {
it('should return data', async () => {
const data = [
{
id: 1,
price: '1',
},
{
id: 2,
price: '2',
},
];
jest.doMock('../data/mock.json', () => {
return {
__esModule: true,
default: data,
};
});
await import('../data/mock.json');
await expect(something()).resolves.toEqual(data);
});
it('should return error', async () => {
jest.doMock('../data/mock.json', () => ({
__esModule: true,
default: undefined,
}));
await import('../data/mock.json');
await expect(something()).resolves.toBe('error is here');
});
});
});
not sure why: but it doesn't mock json import inside my code, that I wish to test.不知道为什么:但它不会在我的代码中模拟 json 导入,我希望测试。 What I do wrong and how to make this import mocked 'conditionally'?
我做错了什么以及如何使这个导入“有条件地”模拟? because if I mock it at the top of the file (nearby imports) - it will work but will be the same for all test cases while I need to make this data different in different test cases.
因为如果我在文件顶部(附近的导入)模拟它 - 它会起作用,但对于所有测试用例都是相同的,而我需要在不同的测试用例中使这些数据不同。
jest.doMock
cannot affect something
because it already uses original mock.json
and needs to be reimported, while reimporting mock.json
in tests cannot affect anything on its own. jest.doMock
不能影响something
因为它已经使用了原始的mock.json
并且需要重新导入,而在测试中重新导入mock.json
本身不会影响任何东西。
It should be:它应该是:
jest.doMock('../data/mock.json', () => ({
__esModule: true,
default: undefined,
}));
const { something } = await import('./handler');
await expect(something()).resolves.toBe('error is here');
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.