最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论