Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to disable React Native YellowBox messages in jest tests

I know how to disable YellowBox warning when running in the device:

YellowBox.ignoreWarnings(ignoredYellowBox);

But I don't know how to silence them in a jest test. There are some deprecation warnings that we cannot deal with atm and they are making our tests very noisy. I'd rather not block every YellowBox warning from our tests, but if necessary, that would work too.

like image 587
Kevin Avatar asked Oct 19 '25 01:10

Kevin


2 Answers

It is a pretty annoying thing. This is what we came up with:

const warnings = [
  'Warning: NetInfo has been extracted from react-native core and will be removed in a future release.',
  'inside a test was not wrapped in act(...).',
];
const oldError = console.error;
jest.spyOn(console, 'error').mockImplementation((...args) => {
  const string = args.join(' ');
  if (warnings.some(warning => string.match(warning))) return;
  oldError(...args);
});

Add that snippet to your jest setup file, and edit the warnings array as appropriate for your situation.

like image 178
aet Avatar answered Oct 21 '25 01:10

aet


For future readers, there is a simple way to do this.

jest.spyOn(console, 'warn').mockImplementation(() => {})
jest.spyOn(console, 'error').mockImplementation(() => {})

For TypeScript:

jest.spyOn(console, 'warn').mockImplementation(() => undefined)
jest.spyOn(console, 'error').mockImplementation(() => undefined)

Remember that by using an approach like this you are disabling all console errors and warnings. If you want to keep other errors and warnings, just use the first answer in this question.

like image 33
Carlos Querioz Avatar answered Oct 20 '25 23:10

Carlos Querioz