typescript - How to mock Axios error response when using VueQuery - Stack Overflow

I am implementing VueQuery in my application. Now I am trying to write unit tests for this. The success

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?

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745570284a4633640.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信