Skip to content

Commit

Permalink
chore: add single versioned implementation of act for DevTools tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxyq committed Feb 1, 2024
1 parent d29f7d9 commit ce11195
Showing 1 changed file with 46 additions and 0 deletions.
46 changes: 46 additions & 0 deletions packages/react-devtools-shared/src/__tests__/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,13 +7,17 @@
* @flow
*/

import semver from 'semver';

import typeof ReactTestRenderer from 'react-test-renderer';

import type {FrontendBridge} from 'react-devtools-shared/src/bridge';
import type Store from 'react-devtools-shared/src/devtools/store';
import type {ProfilingDataFrontend} from 'react-devtools-shared/src/devtools/views/Profiler/types';
import type {ElementType} from 'react-devtools-shared/src/frontend/types';

import {ReactVersion} from '../../../../ReactVersions';

export function act(
callback: Function,
recursivelyFlush: boolean = true,
Expand Down Expand Up @@ -73,6 +77,48 @@ export async function actAsync(
}
}

const requestedReactVersion = process.env.REACT_VERSION || ReactVersion;
export async function actImplementation(callback: Function): Promise<void> {
// This is for React < 18, where act was distributed in react-dom/test-utils.
if (semver.lt(requestedReactVersion, '18.0.0')) {
return require('react-dom/test-utils').act(callback);
}

const React = require('React');
// This is for React 18, where act was distributed in react as unstable.
if (React.unstable_act) {
return React.unstable_act(callback);
}

// This is for React > 18, where act is marked as stable.
if (React.act) {
return React.act(callback);
}

throw new Error("Couldn't find any available act implementation");
}

export async function actModern(callback: Function): Promise<void> {
const {act: actTestRenderer} = require('react-test-renderer');

// act from react-test-renderer has some side effects on React DevTools
// it injects the renderer for DevTools, see ReactTestRenderer.js
await actImplementation(() => {
actTestRenderer(() => {
callback();
});
});

// Flush Bridge operations
while (jest.getTimerCount() > 0) {
await actImplementation(() => {
actTestRenderer(() => {
jest.runAllTimers();
});
});
}
}

export function beforeEachProfiling(): void {
// Mock React's timing information so that test runs are predictable.
jest.mock('scheduler', () => jest.requireActual('scheduler/unstable_mock'));
Expand Down

0 comments on commit ce11195

Please sign in to comment.