如何在 describe 或 it 块中使用 jest.mock?
How do I use jest.mock within a describe or it block?
我正在使用 typescript 和 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);
});
但是,我想在 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);
});
我收到一条错误消息,指出模拟不再被使用或启动。如何在“describe”或“it”块中使用“jest.mock”?
您可以在 it
或 test
块中使用 processDataSpy.mockImplementation
。
// 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);
});
我正在使用 typescript 和 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);
});
但是,我想在 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);
});
我收到一条错误消息,指出模拟不再被使用或启动。如何在“describe”或“it”块中使用“jest.mock”?
您可以在 it
或 test
块中使用 processDataSpy.mockImplementation
。
// 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);
});