Dav*_*ave 7 unit-testing mocking typescript ts-jest
我正在使用打字稿和玩笑。我有两个文件,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);
});
Run Code Online (Sandbox Code Playgroud)
但是,我想在 processDataSpy 中模拟不同的结果。我正在测试上面的情况并引发错误,但我想测试不引发错误的情况。如何测试多个案例?将“jest.mock”移动到“it”块内会破坏测试......
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);
});
Run Code Online (Sandbox Code Playgroud)
我收到一条错误消息,表明该模拟不再被使用或启动。如何在“describe”或“it”块中使用“jest.mock”?
您可以使用processDataSpy.mockImplementation
insideit
或test
block。
// Optionally reset the mock before each test
beforeEach(() => {
processDataSpy.mockReset();
});
it('Another use case', async () => {
processDataSpy.mockImplementation(() => {
throw new Error('Another error');
})
const result = await sendUserData(
data
);
expect(result).toBe(false);
});
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
8035 次 |
最近记录: |