I am implementing VueQuery in my application. Now I am trying to write unit tests for this. The success case works fine, but when I mock an error case it seems to error is not being handled by VueQuery.
I am passing an Axios method to my useQuery instance. The in my unit test I mock my API client as a spy and mock the rejected value while passing an AxiosError object.
This is my unit test:
it('show an error message when an error response is returned', async () => {
const spy = vi.spyOn(PersonApi.prototype, 'createPerson');
spy.mockRejectedValueOnce({
isAxiosError: true,
toJSON: () => ({}),
name: 'AxiosError',
message: 'Request failed with status code 400',
response: {
data: {message: 'Error'},
status: 400,
statusText: 'Bad Request',
headers: {},
config: {headers: {} as AxiosRequestHeaders},
request: {},
},
config: {headers: {} as AxiosRequestHeaders}
} as AxiosError);
wrapper = createComponent();
await flushPromises();
expect(spy).toHaveBeenCalledOnce();
expect(wrapper.find('#error-status-message').exists()).toBe(true);
});
And this is the useQuery instance:
const {isLoading, mutateAsync, isError} = useMutation({
mutationKey: ['createPerson'],
mutationFn: async () => await personApi.createPerson({
id,
})
});
When I run the test I get a message in the Run console of 'Request failed with status code 400', which is technically correct but it seems the entire test is failing because the exception is not being handled. Anyone has an idea?