我试图测试是否已使用jest模拟调用了我的API服务,我看到的大多数示例都使用jest.mock('axios'),我不想依赖Axios库,但要独立任何这一切。当前,我的输出断言是0而不是1。有人可以看到我可能在哪里出错吗?
service.ts
import api from './api';
const postRequest = async (id: string, name: string) => {
const response = await api.post(`contests/${id}/joinedteams/${teamId}`)
.then((res) => res.status)
.catch((error) => Promise.reject(error));
return response;
};
export default postRequest;
Form.ts
const onSubmit = async (formData: any) => {
const nameId = formData.name;
await postJoinContest(id, nameId);
handleModalClose();
};
test.ts
const MockService = postRequest: jest.fn((_id: string, teamId: string) => console.log('called'))
jest.mock('../../services/', () => ({
__esModule: true,
default: {
postRequest: (id: string, name: string) => MockService
}
}));
it('submit a valid form', async () => {
render(component);
fireEvent.click(screen.getByRole('button'));
await expect(MockService).toHaveBeenCalled();
expect(mockService.postJoinContest).toHaveBeenCalledWith('6fafae7c-495e-4e18-9709-3c08b66b3b3d', 'paul');
});