Skip to content

Commit 608edcc

Browse files
authored
[tests] add assertConsole<method>Dev helpers (#28732)
## Overview **Internal React repo tests only** Depends on #28710 Adds three new assertions: - `assertConsoleLogDev` - `assertConsoleWarnDev` - `assertConsoleErrorDev` These will replace this pattern: ```js await expect(async () => { await expect(async () => { await act(() => { root.render(<Fail />) }); }).toThrow(); }).toWarnDev('Warning'); ``` With this: ```js await expect(async () => { await act(() => { root.render(<Fail />) }); }).toThrow(); assertConsoleWarnDev('Warning'); ``` It works similar to our other `assertLog` matchers which clear the log and assert on it, failing the tests if the log is not asserted before the test ends. ## Diffs There are a few improvements I also added including better log diffs and more logging. When there's a failure, the output will look something like: <img width="655" alt="Screenshot 2024-04-03 at 11 50 08 AM" src="https://github.com/facebook/react/assets/2440089/0c4bf1b2-5f63-4204-8af3-09e0c2d752ad"> Check out the test suite for snapshots of all the failures we may log.
1 parent da69b6a commit 608edcc

File tree

6 files changed

+2881
-16
lines changed

6 files changed

+2881
-16
lines changed

packages/internal-test-utils/ReactInternalTestUtils.js

+24-1
Original file line numberDiff line numberDiff line change
@@ -10,8 +10,14 @@ import {diff} from 'jest-diff';
1010
import {equals} from '@jest/expect-utils';
1111
import enqueueTask from './enqueueTask';
1212
import simulateBrowserEventDispatch from './simulateBrowserEventDispatch';
13-
13+
import {
14+
clearLogs,
15+
clearWarnings,
16+
clearErrors,
17+
createLogAssertion,
18+
} from './consoleMock';
1419
export {act} from './internalAct';
20+
const {assertConsoleLogsCleared} = require('internal-test-utils/consoleMock');
1521

1622
import {thrownErrors, actingUpdatesScopeDepth} from './internalAct';
1723

@@ -24,6 +30,7 @@ function assertYieldsWereCleared(caller) {
2430
Error.captureStackTrace(error, caller);
2531
throw error;
2632
}
33+
assertConsoleLogsCleared();
2734
}
2835

2936
export async function waitForMicrotasks() {
@@ -317,6 +324,22 @@ ${diff(expectedLog, actualLog)}
317324
throw error;
318325
}
319326

327+
export const assertConsoleLogDev = createLogAssertion(
328+
'log',
329+
'assertConsoleLogDev',
330+
clearLogs,
331+
);
332+
export const assertConsoleWarnDev = createLogAssertion(
333+
'warn',
334+
'assertConsoleWarnDev',
335+
clearWarnings,
336+
);
337+
export const assertConsoleErrorDev = createLogAssertion(
338+
'error',
339+
'assertConsoleErrorDev',
340+
clearErrors,
341+
);
342+
320343
// Simulates dispatching events, waiting for microtasks in between.
321344
// This matches the browser behavior, which will flush microtasks
322345
// between each event handler. This will allow discrete events to

0 commit comments

Comments
 (0)