Hi everyone i am new in react and unit test. I am trying to implement unit test in react using vitest and react testing library. I just confused how to unit test async axios api call.
so basically i have axios api called submit api
export const submitapi = (obj) =>
axios.put("submit", obj);
which is called through component hooks useSubmit.js
export const useSubmit = () => {
const callSave = ({ fields, setError }) => {
submitapi(fields)
.then((res) => {
if (res.data.isError) {
//show error message
return;
} else {
//success message
//navigate home;
}
})
.catch((e) => {
//show error message
});
};
const onSubmit = ({ fields, setError, getValues }) => {
// it has some validation
callSave({ fields, setError });
};
return { onSubmit };
};
so far for unit test i have mock api for submitapi
export const submitapi = () =>
vi.fn().mockResolvedValue({
data: {
responseData:
{
isError:false
},
},
});
and unit test with vitest
const mod = await vi.importActual("react-router-dom");
return {
...mod,
useParams: () => ({
asbId: "1",
}),
};
});
vi.mock('~/api/submitapi');
const {
result: {
current: { ContextProvider },
},
} = renderHook(() => useProviders());
describe("myForm", () => {
afterEach(() => {
cleanup();
});
test("should call submit", async () => {
render(
<ContextProvider>
<MyForm />
</ContextProvider>,
{ wrapper: BrowserRouter },
);
userEvent.click(screen.getByText("Submit"));
await waitFor(()=>{
expect(submitapi).toHaveBeenCalledWith(testData);
})
});
so far i am getting error [Function submitapi] is not a spy or a call to a spy!
Thank you in advance.