1
1
import * as React from "react" ;
2
2
import * as DeprecatedReactTestUtils from "react-dom/test-utils" ;
3
3
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
-
13
4
type Item = {
14
5
callback : IntersectionObserverCallback ;
15
6
elements : Set < Element > ;
@@ -21,9 +12,14 @@ let isMocking = false;
21
12
const observers = new Map < IntersectionObserver , Item > ( ) ;
22
13
23
14
// 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
+ ) {
25
20
beforeAll ( ( ) => {
26
21
// Use the exposed mock function. Currently, only supports Jest (`jest.fn`) and Vitest with globals (`vi.fn`).
22
+ // @ts -ignore
27
23
if ( typeof jest !== "undefined" ) setupIntersectionMocking ( jest . fn ) ;
28
24
else if ( typeof vi !== "undefined" ) {
29
25
setupIntersectionMocking ( vi . fn ) ;
@@ -107,10 +103,21 @@ export function resetIntersectionMocking() {
107
103
observers . clear ( ) ;
108
104
}
109
105
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 ;
114
121
}
115
122
116
123
function triggerIntersection (
@@ -168,8 +175,8 @@ function triggerIntersection(
168
175
}
169
176
170
177
// 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 ) ) ;
173
180
else item . callback ( entries , observer ) ;
174
181
}
175
182
/**
0 commit comments