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 > ;
@@ -20,10 +11,17 @@ let isMocking = false;
20
11
21
12
const observers = new Map < IntersectionObserver , Item > ( ) ;
22
13
23
- // If we are running in a valid testing environment, we can mock the IntersectionObserver.
24
- if ( typeof beforeAll !== "undefined" && typeof afterEach !== "undefined" ) {
14
+ /*
15
+ ** If we are running in a valid testing environment, we can automate mocking the IntersectionObserver.
16
+ */
17
+ if (
18
+ typeof window !== "undefined" &&
19
+ typeof beforeAll !== "undefined" &&
20
+ typeof afterEach !== "undefined"
21
+ ) {
25
22
beforeAll ( ( ) => {
26
23
// Use the exposed mock function. Currently, only supports Jest (`jest.fn`) and Vitest with globals (`vi.fn`).
24
+ // @ts -ignore
27
25
if ( typeof jest !== "undefined" ) setupIntersectionMocking ( jest . fn ) ;
28
26
else if ( typeof vi !== "undefined" ) {
29
27
setupIntersectionMocking ( vi . fn ) ;
@@ -35,6 +33,23 @@ if (typeof beforeAll !== "undefined" && typeof afterEach !== "undefined") {
35
33
} ) ;
36
34
}
37
35
36
+ function getActFn ( ) {
37
+ if (
38
+ ! (
39
+ typeof window !== "undefined" &&
40
+ // @ts -ignore
41
+ window . IS_REACT_ACT_ENVIRONMENT
42
+ )
43
+ ) {
44
+ return undefined ;
45
+ }
46
+ // @ts -ignore - Older versions of React don't have the `act` method, so TypeScript will complain about it
47
+ return typeof React . act === "function"
48
+ ? // @ts -ignore
49
+ React . act
50
+ : DeprecatedReactTestUtils . act ;
51
+ }
52
+
38
53
function warnOnMissingSetup ( ) {
39
54
if ( isMocking ) return ;
40
55
console . error (
@@ -107,12 +122,6 @@ export function resetIntersectionMocking() {
107
122
observers . clear ( ) ;
108
123
}
109
124
110
- function getIsReactActEnvironment ( ) {
111
- return Boolean (
112
- typeof window !== "undefined" && window . IS_REACT_ACT_ENVIRONMENT ,
113
- ) ;
114
- }
115
-
116
125
function triggerIntersection (
117
126
elements : Element [ ] ,
118
127
trigger : boolean | number ,
@@ -168,8 +177,8 @@ function triggerIntersection(
168
177
}
169
178
170
179
// Trigger the IntersectionObserver callback with all the entries
171
- if ( act && getIsReactActEnvironment ( ) )
172
- act ( ( ) => item . callback ( entries , observer ) ) ;
180
+ const act = getActFn ( ) ;
181
+ if ( act ) act ( ( ) => item . callback ( entries , observer ) ) ;
173
182
else item . callback ( entries , observer ) ;
174
183
}
175
184
/**
0 commit comments