diff --git a/src/test-utils.ts b/src/test-utils.ts index d66c0c85..4969b47a 100644 --- a/src/test-utils.ts +++ b/src/test-utils.ts @@ -1,15 +1,6 @@ import * as React from "react"; import * as DeprecatedReactTestUtils from "react-dom/test-utils"; -declare global { - var IS_REACT_ACT_ENVIRONMENT: boolean; - var jest: { fn: typeof vi.fn } | undefined; -} - -const act = - // @ts-ignore - Older versions of React don't have the `act` method, so TypeScript will complain about it - typeof React.act === "function" ? React.act : DeprecatedReactTestUtils.act; - type Item = { callback: IntersectionObserverCallback; elements: Set; @@ -21,9 +12,14 @@ let isMocking = false; const observers = new Map(); // If we are running in a valid testing environment, we can mock the IntersectionObserver. -if (typeof beforeAll !== "undefined" && typeof afterEach !== "undefined") { +if ( + typeof window !== "undefined" && + typeof beforeAll !== "undefined" && + typeof afterEach !== "undefined" +) { beforeAll(() => { // Use the exposed mock function. Currently, only supports Jest (`jest.fn`) and Vitest with globals (`vi.fn`). + // @ts-ignore if (typeof jest !== "undefined") setupIntersectionMocking(jest.fn); else if (typeof vi !== "undefined") { setupIntersectionMocking(vi.fn); @@ -107,10 +103,21 @@ export function resetIntersectionMocking() { observers.clear(); } -function getIsReactActEnvironment() { - return Boolean( - typeof window !== "undefined" && window.IS_REACT_ACT_ENVIRONMENT, - ); +function getActFn() { + if ( + !( + typeof window !== "undefined" && + // @ts-ignore + window.IS_REACT_ACT_ENVIRONMENT + ) + ) { + return undefined; + } + + // @ts-ignore - Older versions of React don't have the `act` method, so TypeScript will complain about it + return typeof React.act === "function" + ? React.act + : DeprecatedReactTestUtils.act; } function triggerIntersection( @@ -168,8 +175,8 @@ function triggerIntersection( } // Trigger the IntersectionObserver callback with all the entries - if (act && getIsReactActEnvironment()) - act(() => item.callback(entries, observer)); + const act = getActFn(); + if (act) act(() => item.callback(entries, observer)); else item.callback(entries, observer); } /**