Skip to content

Commit

Permalink
[React@18] Improve console.error suppression in react-testing-library…
Browse files Browse the repository at this point in the history
… setup (elastic#201142) (elastic#202600)

In addition to changes introduced by elastic#201142

Reasoning:

This pull request includes changes to the
`packages/kbn-test/src/jest/setup/react_testing_library.js` file to
improve internal error logging suppression from react-testing-library.
In particular,
[this](https://github.com/testing-library/react-hooks-testing-library/blob/1e01273374af4e48a0feb1f2233bf6c76d742167/src/core/console.ts#L1-L4)
suppression logic has been migrated to avoid breaking devUX
expectations.

Tested against elastic#201142 code
changes
  • Loading branch information
kapral18 authored Dec 16, 2024
1 parent 863d047 commit 3a6d27a
Showing 1 changed file with 21 additions and 3 deletions.
24 changes: 21 additions & 3 deletions packages/kbn-test/src/jest/setup/react_testing_library.js
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,11 @@ jest.mock('@testing-library/react', () => {
};
});

const consoleFilters = [
/^The above error occurred in the <.*?> component:/, // error boundary output
/^Error: Uncaught .+/, // jsdom output
];

// This is a workaround to run tests with React 17 and the latest @testing-library/react
// And prevent the act warnings that were supposed to be muted by @testing-library
// The testing library mutes the act warnings in some cases by setting IS_REACT_ACT_ENVIRONMENT which is React@18 feature https://github.com/testing-library/react-testing-library/pull/1137/
Expand All @@ -44,14 +49,27 @@ jest.mock('@testing-library/react', () => {
// NOTE: we're not muting all the act warnings but only those that testing-library wanted to mute
const originalConsoleError = console.error;
console.error = (...args) => {
const message = args[0]?.toString();

if (global.IS_REACT_ACT_ENVIRONMENT === false) {
if (
args[0].toString().includes('Warning: An update to %s inside a test was not wrapped in act')
) {
if (message.includes('Warning: An update to %s inside a test was not wrapped in act')) {
return;
}
}

// Additionally this is a restoration of the original console.error suppression
// expected by the usage of renderHook from react-hooks-testing-library
// which has been moved into latest react-testing-library but the suppression
// of the console.error was not moved with it.
//
// So adding by example from the original implementation:
// https://github.com/testing-library/react-hooks-testing-library/blob/1e01273374af4e48a0feb1f2233bf6c76d742167/src/core/console.ts
// with a slight modification to catch non-string errors as well

if (message && consoleFilters.some((filter) => filter.test(message))) {
return;
}

originalConsoleError(...args);
};

Expand Down

0 comments on commit 3a6d27a

Please sign in to comment.