【发布时间】:2021-06-24 20:09:08
【问题描述】:
我正在使用打字稿和玩笑。我有两个文件users.service.ts,它导入producer.ts。我想在 producer.ts 中模拟一个函数。这很好用
import { sendUserData } from './users.service';
const processDataSpy = jest.fn().mockImplementation(() => {
throw new Error('failed');
});
jest.mock('../users/manager', () => ({
sendEvent: async (arg1: string, arg2: string, arg3: any) =>
processDataSpy(arg1, arg2, arg3),
}));
describe('users.service', () => {
it('invokes endpoint and returns proper data if unsuccessful', async () => {
const result = await sendUserData(
data
);
expect(result).toBe(false);
});
但是,我想在 processDataSpy 中模拟不同的结果。我正在测试上面抛出错误的案例,但我想测试没有抛出错误的案例。如何测试多个案例?在我的“it”块中移动“jest.mock”会破坏测试......
it('invokes endpoint and returns proper data if unsuccessful', async () => {
jest.mock('../users/manager', () => ({
sendEvent: async (arg1: string, arg2: string, arg3: any) =>
processDataSpy(arg1, arg2, arg3),
}));
...
const result = await sendUserData(
data
);
expect(result).toBe(false);
});
我收到一条错误消息,表明不再使用或启动模拟。如何在“describe”或“it”块中使用“jest.mock”?
【问题讨论】:
标签: typescript unit-testing mocking ts-jest