Skip to content

Commit

Permalink
chore: add version render implementation for DevTools tests
Browse files Browse the repository at this point in the history
  • Loading branch information
hoxyq committed Feb 2, 2024
1 parent 319ea12 commit 2047c90
Showing 1 changed file with 125 additions and 0 deletions.
125 changes: 125 additions & 0 deletions packages/react-devtools-shared/src/__tests__/utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,131 @@ export async function actAsync(
}
}

type RenderImplementation = {
render: (elements: React.Node) => () => void,
unmount: () => void,
createContainer: () => void,
getContainer: () => ?HTMLElement,
};

export function getLegacyRenderImplementation(): RenderImplementation {
let ReactDOM;
let container;
let unmounted = false;

beforeEach(() => {
ReactDOM = require('react-dom');

createContainer();
});

afterEach(() => {
if (!unmounted) {
unmount();
}

ReactDOM = null;
container = null;
});

function render(elements: React.Node) {
withErrorsOrWarningsIgnored(
['ReactDOM.render is no longer supported in React 18'],
() => {
ReactDOM.render(elements, container);
},
);

return unmount;
}

function unmount() {
unmounted = true;

ReactDOM.unmountComponentAtNode(container);
document.body.removeChild(container);
}

function createContainer() {
unmounted = false;

container = document.createElement('div');
document.body.appendChild(container);
}

function getContainer() {
return container;
}

return {
render,
unmount,
createContainer,
getContainer,
};
}

export function getModernRenderImplementation(): RenderImplementation {
let ReactDOMClient;
let container;
let root;
let unmounted = false;

beforeEach(() => {
ReactDOMClient = require('react-dom/client');

createContainer();
});

afterEach(() => {
if (!unmounted) {
unmount();
}

ReactDOMClient = null;
container = null;
root = null;
});

function render(elements: React.Node) {
root.render(elements);

return unmount;
}

function unmount() {
unmounted = true;

root.unmount();
document.body.removeChild(container);
}

function createContainer() {
unmounted = false;

container = document.createElement('div');
document.body.appendChild(container);

root = ReactDOMClient.createRoot(container);
}

function getContainer() {
return container;
}

return {
render,
unmount,
createContainer,
getContainer,
};
}

export const getVersionedRenderImplementation: () => RenderImplementation =
semver.lt(requestedReactVersion, '18.0.0')
? getLegacyRenderImplementation
: getModernRenderImplementation;

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 2047c90

Please sign in to comment.