@@ -11,26 +11,32 @@ let isMocking = false;
11
11
12
12
const observers = new Map < IntersectionObserver , Item > ( ) ;
13
13
14
+ // Store a reference to the original `IntersectionObserver` so we can restore it later.
15
+ // This can be relevant if testing in a browser environment, where you actually have a native `IntersectionObserver`.
16
+ const originalIntersectionObserver =
17
+ typeof window !== "undefined" ? window . IntersectionObserver : undefined ;
18
+
14
19
/*
15
20
** If we are running in a valid testing environment, we can automate mocking the IntersectionObserver.
16
21
*/
17
22
if (
18
23
typeof window !== "undefined" &&
19
24
typeof beforeAll !== "undefined" &&
25
+ typeof beforeEach !== "undefined" &&
20
26
typeof afterEach !== "undefined"
21
27
) {
22
- beforeAll ( ( ) => {
23
- // Use the exposed mock function. Currently, only supports Jest (`jest.fn`) and Vitest with globals (`vi.fn`).
28
+ const initMocking = ( ) => {
29
+ // Use the exposed mock function. Currently, it supports Jest (`jest.fn`) and Vitest with globals (`vi.fn`).
24
30
// @ts -ignore
25
31
if ( typeof jest !== "undefined" ) setupIntersectionMocking ( jest . fn ) ;
26
32
else if ( typeof vi !== "undefined" ) {
27
33
setupIntersectionMocking ( vi . fn ) ;
28
34
}
29
- } ) ;
35
+ } ;
30
36
31
- afterEach ( ( ) => {
32
- resetIntersectionMocking ( ) ;
33
- } ) ;
37
+ beforeAll ( initMocking ) ;
38
+ beforeEach ( initMocking ) ;
39
+ afterEach ( resetIntersectionMocking ) ;
34
40
}
35
41
36
42
function getActFn ( ) {
@@ -76,6 +82,7 @@ afterEach(() => {
76
82
* @param mockFn The mock function to use. Defaults to `vi.fn`.
77
83
*/
78
84
export function setupIntersectionMocking ( mockFn : typeof vi . fn ) {
85
+ if ( isMocking ) return ;
79
86
window . IntersectionObserver = mockFn ( ( cb , options = { } ) => {
80
87
const item = {
81
88
callback : cb ,
@@ -122,6 +129,17 @@ export function resetIntersectionMocking() {
122
129
observers . clear ( ) ;
123
130
}
124
131
132
+ /**
133
+ * Destroy the IntersectionObserver mock function, and restore the original browser implementation of `IntersectionObserver`.
134
+ * You can use this to opt of mocking in a specific test.
135
+ **/
136
+ export function destroyIntersectionMocking ( ) {
137
+ resetIntersectionMocking ( ) ;
138
+ // @ts -ignore
139
+ window . IntersectionObserver = originalIntersectionObserver ;
140
+ isMocking = false ;
141
+ }
142
+
125
143
function triggerIntersection (
126
144
elements : Element [ ] ,
127
145
trigger : boolean | number ,
0 commit comments