Skip to content

Commit 945e9bf

Browse files
authored
chore: Fix console.error pollution (#1077)
* chore: Fix console.error pollution Signed-off-by: Tim Chan <[email protected]> * Relocated to src/test-utils. Signed-off-by: Tim Chan <[email protected]> --------- Signed-off-by: Tim Chan <[email protected]>
1 parent 682502f commit 945e9bf

File tree

2 files changed

+54
-4
lines changed

2 files changed

+54
-4
lines changed
Lines changed: 35 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,35 @@
1+
/*
2+
* Mocks console.error and silences known errors.
3+
*
4+
* Apply this utility to mute known errors and avoid polluting the test output.
5+
*/
6+
export const mockConsoleError = ({
7+
silencedErrorRegexes,
8+
}: {
9+
silencedErrorRegexes: RegExp[];
10+
}) => {
11+
// eslint-disable-next-line no-console
12+
const consoleError = console.error;
13+
14+
const consoleErrorImpl = (...data: any[]) => {
15+
const dataString = data.toString();
16+
let shouldIgnore = false;
17+
18+
for (const regex of silencedErrorRegexes) {
19+
if (regex.test(dataString)) {
20+
shouldIgnore = true;
21+
break;
22+
}
23+
}
24+
25+
if (!shouldIgnore) {
26+
consoleError(...data);
27+
}
28+
};
29+
30+
const spy = jest.spyOn(console, 'error').mockImplementation(consoleErrorImpl);
31+
32+
return {
33+
restore: () => spy.mockRestore(),
34+
};
35+
};

src/views/domain-page/domain-page-tabs/__tests__/domain-page-tabs.test.tsx

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import { render, screen, userEvent } from '@/test-utils/rtl';
66

77
import ErrorBoundary from '@/components/error-boundary/error-boundary';
88
import { type GetConfigResponse } from '@/route-handlers/get-config/get-config.types';
9+
import { mockConsoleError } from '@/test-utils/mock-console-error';
910

1011
import DomainPageTabs from '../domain-page-tabs';
1112

@@ -141,11 +142,25 @@ describe(DomainPageTabs.name, () => {
141142
});
142143

143144
it('handles errors gracefully', async () => {
144-
await setup({ error: true });
145+
// Mute console.error to avoid polluting the test output.
146+
const silencedErrorRegexes = [
147+
/RequestError: Failed to fetch config/,
148+
/The above error occurred in the <DomainPageTabs> component/,
149+
];
150+
const { restore: restoreConsoleError } = mockConsoleError({
151+
silencedErrorRegexes,
152+
});
153+
154+
try {
155+
await setup({ error: true });
145156

146-
expect(
147-
await screen.findByText('Error: Failed to fetch config')
148-
).toBeInTheDocument();
157+
expect(
158+
await screen.findByText('Error: Failed to fetch config')
159+
).toBeInTheDocument();
160+
} finally {
161+
// Be sure to restore the console.error.
162+
restoreConsoleError();
163+
}
149164
});
150165

151166
it('renders the help button as endEnhancer', async () => {

0 commit comments

Comments
 (0)