Ben
Ben

Reputation: 5192

vitest + msw / testing reactQuery (axios) hooks using renderHook / unable to avoid error logging from test suite

Using a custom logger as follow for our test suite :

export const queryClient = new QueryClient({
  logger: {
    log: console.log,
    warn: console.warn,
    error: () => {}
  }
});

Mocking errors as follow within msw :

rest.get('/some/api/route', (_req, res, ctx) => {
    return res.once(ctx.status(500), ctx.json({ errorMessage: 'some error' }));
  })

We override the handlers for errors :

it("should return error", () => {
  server.use(...errorHandlers);

    const { result } = renderHook(() =>
      query({
        url: '/some/api/routes',
        options: { retry: false }
      })
    );

  ...some assertions
});

Out tests are ok, but the network errors are still appearing in the console when running the test suite (the display is thrashed) :

    Error: Request failed with status code 500
        at createError (.../node_modules/axios/lib/core/createError.js:16:15)
        at settle (.../node_modules/axios/lib/core/settle.js:17:12)
        at XMLHttpRequestOverride.onloadend (.../node_modules/axios/lib/ad
   ... super long logging ...

Such non blocking issue is tackled in other projects using jest as the custom queryClient logger does the job; it seems that it behaves differently using vitest. Does anyone knows which part is the culprit in that context ? What should be done ?

Upvotes: 0

Views: 1247

Answers (1)

TkDodo
TkDodo

Reputation: 29008

passing a custom logger to the QueryClient is a feature that was introduced in v4.

For v3, you need to call setLogger, which is exported from react-query:

https://react-query-v3.tanstack.com/reference/setLogger

 import { setLogger } from 'react-query'
 
 setLogger({
    log: console.log,
    warn: console.warn,
    error: () => {}
 })

Upvotes: 1

Related Questions