From 8498746a7478a33ad64b3e3e99a4a7a02e5ae41a Mon Sep 17 00:00:00 2001 From: Jason Addleman Date: Mon, 6 May 2024 11:09:47 -0400 Subject: [PATCH] Use act from 'react' if available --- .changeset/flat-paws-exercise.md | 5 +++++ packages/react-testing/src/compat.ts | 11 +++++++++++ packages/react-testing/src/root.tsx | 9 +++++++-- 3 files changed, 23 insertions(+), 2 deletions(-) create mode 100644 .changeset/flat-paws-exercise.md diff --git a/.changeset/flat-paws-exercise.md b/.changeset/flat-paws-exercise.md new file mode 100644 index 0000000000..555514b31f --- /dev/null +++ b/.changeset/flat-paws-exercise.md @@ -0,0 +1,5 @@ +--- +'@shopify/react-testing': minor +--- + +Change act to use from 'react' if it exists, fallback to 'react-dom/test-utils' diff --git a/packages/react-testing/src/compat.ts b/packages/react-testing/src/compat.ts index 77d054a4f7..b5c58bc600 100644 --- a/packages/react-testing/src/compat.ts +++ b/packages/react-testing/src/compat.ts @@ -1,6 +1,7 @@ import ReactDOM from 'react-dom'; import React from 'react'; import type {Root as ReactRoot} from 'react-dom/client'; +import {act as oldAct} from 'react-dom/test-utils'; import type {ReactInstance, Fiber} from './types'; @@ -38,6 +39,16 @@ export function createRoot(element: HTMLElement): ReactRoot { export const isLegacyReact = parseInt(React.version, 10) < 18; +export const act: typeof oldAct = (() => { + try { + // eslint-disable-next-line @typescript-eslint/no-var-requires + const {act} = require('react'); + return act ?? oldAct; + } catch { + return oldAct; + } +})(); + // https://github.com/facebook/react/blob/12adaffef7105e2714f82651ea51936c563fe15c/packages/shared/enqueueTask.js#L13 let enqueueTaskImpl: any = null; diff --git a/packages/react-testing/src/root.tsx b/packages/react-testing/src/root.tsx index 884f000c51..56c4ad6d9d 100644 --- a/packages/react-testing/src/root.tsx +++ b/packages/react-testing/src/root.tsx @@ -1,12 +1,17 @@ import React from 'react'; import {flushSync} from 'react-dom'; import type {Root as ReactRoot} from 'react-dom/client'; -import {act} from 'react-dom/test-utils'; import {findCurrentFiberUsingSlowPath} from 'react-reconciler/reflection.js'; import {TestWrapper} from './TestWrapper'; import {Element} from './element'; -import {createRoot, getInternals, enqueueTask, isLegacyReact} from './compat'; +import { + createRoot, + getInternals, + enqueueTask, + isLegacyReact, + act, +} from './compat'; import type { Fiber, Node,