Skip to content

Commit

Permalink
[tests] add assertConsole<method>Dev helpers (#28732)
Browse files Browse the repository at this point in the history
## 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.
  • Loading branch information
rickhanlonii committed Apr 11, 2024
1 parent 49a47a7 commit a580a8d
Show file tree
Hide file tree
Showing 6 changed files with 2,881 additions and 16 deletions.
25 changes: 24 additions & 1 deletion packages/internal-test-utils/ReactInternalTestUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,14 @@ import {diff} from 'jest-diff';
import {equals} from '@jest/expect-utils';
import enqueueTask from './enqueueTask';
import simulateBrowserEventDispatch from './simulateBrowserEventDispatch';

import {
clearLogs,
clearWarnings,
clearErrors,
createLogAssertion,
} from './consoleMock';
export {act} from './internalAct';
const {assertConsoleLogsCleared} = require('internal-test-utils/consoleMock');

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

Expand All @@ -24,6 +30,7 @@ function assertYieldsWereCleared(caller) {
Error.captureStackTrace(error, caller);
throw error;
}
assertConsoleLogsCleared();
}

export async function waitForMicrotasks() {
Expand Down Expand Up @@ -317,6 +324,22 @@ ${diff(expectedLog, actualLog)}
throw error;
}

export const assertConsoleLogDev = createLogAssertion(
'log',
'assertConsoleLogDev',
clearLogs,
);
export const assertConsoleWarnDev = createLogAssertion(
'warn',
'assertConsoleWarnDev',
clearWarnings,
);
export const assertConsoleErrorDev = createLogAssertion(
'error',
'assertConsoleErrorDev',
clearErrors,
);

// Simulates dispatching events, waiting for microtasks in between.
// This matches the browser behavior, which will flush microtasks
// between each event handler. This will allow discrete events to
Expand Down
Loading

0 comments on commit a580a8d

Please sign in to comment.