throw-on-react-error.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142
  1. /* global fail */
  2. // eslint-disable-next-line no-console
  3. const originalConsoleError = console.error;
  4. // List of `console.error` messages to ignore
  5. // (i.e. don't fail tests when we get these messages)
  6. const IGNORED_ERRORS = [
  7. (message, ...args) =>
  8. typeof message === 'string' &&
  9. message.includes('Warning: ') &&
  10. args[0] === 'CreatableSelect',
  11. message =>
  12. typeof message === 'string' &&
  13. message.includes(
  14. 'The pseudo class ":first-child" is potentially unsafe when doing server-side rendering.'
  15. ),
  16. ];
  17. // This is needed because when we throw the captured error message, it will
  18. // also `console.error` it
  19. const REPEATED_ERROR = 'Error: Uncaught [Error: ';
  20. jest.spyOn(console, 'error').mockImplementation((message, ...args) => {
  21. const isIgnored = IGNORED_ERRORS.some(checkFn => checkFn(message, ...args));
  22. if (
  23. typeof message === 'string' &&
  24. message.indexOf(REPEATED_ERROR) !== 0 &&
  25. !isIgnored
  26. ) {
  27. originalConsoleError(message, ...args);
  28. const err = new Error('Warnings received from console.error()');
  29. const lines = err.stack?.split('\n');
  30. const startIndex = lines?.findIndex(line => line.includes('tests/js/spec'));
  31. err.stack = ['\n', lines?.[0], ...lines?.slice(startIndex)].join('\n');
  32. // `fail` is a global from jest/jasmine
  33. // eslint-disable-next-line jest/no-jasmine-globals
  34. fail(err);
  35. }
  36. });