Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I mute react-query console errors when a promise rejects?

I'm testing a custom hook powered by react-query. I needed to test its rollback behavior when a promise rejects. Unfortunately, react-query logs rejected promises to the console using console.error, which dirties up my test output. How can I prevent react-query from logging rejected promises as console errors?

like image 283
Nathan Arthur Avatar asked Sep 14 '25 22:09

Nathan Arthur


1 Answers

react-query has a method called setLogger (used to be called setConsole) that you can use to achieve this.

To mute all console messages from react-query:

setLogger({
    log: () => {},
    warn: () => {},
    error: () => {},
});

To again unmute react-query:

setLogger(window.console);

If you wish to only mute some levels and not others, you can, by setting any combination of empty functions and window.console functions. For example:

setLogger({
    log: () => {},
    warn: window.console.warn,
    error: window.console.error,
});

If you only want to mute the logger for a single test, these calls can be made at the beginning and end of the test in question.

If you'd rather mute the logger for an entire test file, you can use Jest's setup and teardown methods:

beforeAll(() => {
  setLogger({
    log: () => {},
    warn: () => {},
    error: () => {},
  });
});

afterAll(() => {
  setLogger(window.console);
});

If you wish to mute the logger for all tests in your suite, you can add the call to a test setup file (named, for example, testSetup.js), and then add the following to your jest configuration:

setupFilesAfterEnv: ['<rootDir>/testSetup.js'],

I personally created a helper function to use in my tests (TypeScript):

export async function withMutedReactQueryLogger(
  func: () => Promise<any>
): Promise<any> {
  const noop = () => {
    // do nothing
  };

  setLogger({
    log: noop,
    warn: noop,
    error: noop,
  });

  const result = await func();

  setLogger(window.console);

  return result;
}

I use it like this:

test('test something', async () => {
  await withMutedReactQueryLogger(async () => {
    // write my test here
  })
})
like image 191
Nathan Arthur Avatar answered Sep 17 '25 19:09

Nathan Arthur