Skip to content

Commit

Permalink
fix: ensure browser environment in test-utils
Browse files Browse the repository at this point in the history
  • Loading branch information
thebuilder committed Dec 30, 2024
1 parent 8bafe25 commit 6e459f2
Showing 1 changed file with 23 additions and 16 deletions.
39 changes: 23 additions & 16 deletions src/test-utils.ts
Original file line number Diff line number Diff line change
@@ -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<Element>;
Expand All @@ -21,9 +12,14 @@ let isMocking = false;
const observers = new Map<IntersectionObserver, Item>();

// 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);
Expand Down Expand Up @@ -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(
Expand Down Expand Up @@ -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);
}
/**
Expand Down

0 comments on commit 6e459f2

Please sign in to comment.