How can I the improve speed of error responses when testing with React Query + Axios Mock Adapter?

950 Views Asked by At

I am writing tests for a component that uses React Query with Jest, React Testing Library, and Axios Mock Adapter (All requests are sent with axios)

I want to ensure that an error message appears when axios returns a 500 error, and my test accomplishes this - but the issue is that takes about 8 seconds for the error to actually appear

Here is the test:

  it("should show error message when bad request returned", async () => {
    mock.onGet("/url-example").reply(500);

    renderWithProvider(
        <TestContactUsComponent/>
    );

    expect(screen.getByTitle(/loading spinner/i)).toBeInTheDocument();

    await waitForElementToBeRemoved(
      () => screen.getByTitle(/loading spinner/i),
      { timeout: 10000 }
   );

    await expect(screen.queryByTestId("simple-error")).toBeInTheDocument();
}, 10000);

I console logged the status from useQuery and it returns loading for about 7-8 seconds and then finally returns error, removing the spinner and rendering the error message.

Is there a way to reduce the amount of time this is taking? The tests with 200 requests from axios mock adapter finish almost instantly, so not sure why the 500 error scenario is taking so much longer.

In terms of how the component behaves normally, it renders the error message within about a second, so I don't believe it is an issue within the component itself.

1

There are 1 best solutions below

2
On

per default, react-query does 3 retries with exponential backoff. It is advised to turn off retries globally via the QueryClientProvider - this is in the official docs here. I think yo'd want to do that from within renderWithProvider.

 const queryClient = new QueryClient({
   defaultOptions: {
     queries: {
       // ✅ turns retries off
       retry: false,
     },
   },
 })
 const wrapper = ({ children }) => (
   <QueryClientProvider client={queryClient}>
     {children}
   </QueryClientProvider>
 );