0

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.

serp002
  • 85
  • 8

1 Answers1

0

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>
 );
TkDodo
  • 20,449
  • 3
  • 50
  • 65
  • Thanks for the response! Sorry I should have included the code for the provider - I have that included in the provider already. – serp002 Apr 12 '22 at 00:35
  • sounds like maybe the setting is not picked up because of a typo or so. I see no other way how it could take 8 seconds. please show the code for `renderWithProvider` – TkDodo Apr 13 '22 at 12:16