Skip to content

Commit 6e459f2

Browse files
committed
fix: ensure browser environment in test-utils
1 parent 8bafe25 commit 6e459f2

File tree

1 file changed

+23
-16
lines changed

1 file changed

+23
-16
lines changed

src/test-utils.ts

Lines changed: 23 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,6 @@
11
import * as React from "react";
22
import * as DeprecatedReactTestUtils from "react-dom/test-utils";
33

4-
declare global {
5-
var IS_REACT_ACT_ENVIRONMENT: boolean;
6-
var jest: { fn: typeof vi.fn } | undefined;
7-
}
8-
9-
const act =
10-
// @ts-ignore - Older versions of React don't have the `act` method, so TypeScript will complain about it
11-
typeof React.act === "function" ? React.act : DeprecatedReactTestUtils.act;
12-
134
type Item = {
145
callback: IntersectionObserverCallback;
156
elements: Set<Element>;
@@ -21,9 +12,14 @@ let isMocking = false;
2112
const observers = new Map<IntersectionObserver, Item>();
2213

2314
// If we are running in a valid testing environment, we can mock the IntersectionObserver.
24-
if (typeof beforeAll !== "undefined" && typeof afterEach !== "undefined") {
15+
if (
16+
typeof window !== "undefined" &&
17+
typeof beforeAll !== "undefined" &&
18+
typeof afterEach !== "undefined"
19+
) {
2520
beforeAll(() => {
2621
// Use the exposed mock function. Currently, only supports Jest (`jest.fn`) and Vitest with globals (`vi.fn`).
22+
// @ts-ignore
2723
if (typeof jest !== "undefined") setupIntersectionMocking(jest.fn);
2824
else if (typeof vi !== "undefined") {
2925
setupIntersectionMocking(vi.fn);
@@ -107,10 +103,21 @@ export function resetIntersectionMocking() {
107103
observers.clear();
108104
}
109105

110-
function getIsReactActEnvironment() {
111-
return Boolean(
112-
typeof window !== "undefined" && window.IS_REACT_ACT_ENVIRONMENT,
113-
);
106+
function getActFn() {
107+
if (
108+
!(
109+
typeof window !== "undefined" &&
110+
// @ts-ignore
111+
window.IS_REACT_ACT_ENVIRONMENT
112+
)
113+
) {
114+
return undefined;
115+
}
116+
117+
// @ts-ignore - Older versions of React don't have the `act` method, so TypeScript will complain about it
118+
return typeof React.act === "function"
119+
? React.act
120+
: DeprecatedReactTestUtils.act;
114121
}
115122

116123
function triggerIntersection(
@@ -168,8 +175,8 @@ function triggerIntersection(
168175
}
169176

170177
// Trigger the IntersectionObserver callback with all the entries
171-
if (act && getIsReactActEnvironment())
172-
act(() => item.callback(entries, observer));
178+
const act = getActFn();
179+
if (act) act(() => item.callback(entries, observer));
173180
else item.callback(entries, observer);
174181
}
175182
/**

0 commit comments

Comments
 (0)