@@ -11,26 +11,32 @@ let isMocking = false;
1111
1212const observers = new Map < IntersectionObserver , Item > ( ) ;
1313
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+
1419/*
1520 ** If we are running in a valid testing environment, we can automate mocking the IntersectionObserver.
1621 */
1722if (
1823 typeof window !== "undefined" &&
1924 typeof beforeAll !== "undefined" &&
25+ typeof beforeEach !== "undefined" &&
2026 typeof afterEach !== "undefined"
2127) {
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`).
2430 // @ts -ignore
2531 if ( typeof jest !== "undefined" ) setupIntersectionMocking ( jest . fn ) ;
2632 else if ( typeof vi !== "undefined" ) {
2733 setupIntersectionMocking ( vi . fn ) ;
2834 }
29- } ) ;
35+ } ;
3036
31- afterEach ( ( ) => {
32- resetIntersectionMocking ( ) ;
33- } ) ;
37+ beforeAll ( initMocking ) ;
38+ beforeEach ( initMocking ) ;
39+ afterEach ( resetIntersectionMocking ) ;
3440}
3541
3642function getActFn ( ) {
@@ -76,6 +82,7 @@ afterEach(() => {
7682 * @param mockFn The mock function to use. Defaults to `vi.fn`.
7783 */
7884export function setupIntersectionMocking ( mockFn : typeof vi . fn ) {
85+ if ( isMocking ) return ;
7986 window . IntersectionObserver = mockFn ( ( cb , options = { } ) => {
8087 const item = {
8188 callback : cb ,
@@ -122,6 +129,17 @@ export function resetIntersectionMocking() {
122129 observers . clear ( ) ;
123130}
124131
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+
125143function triggerIntersection (
126144 elements : Element [ ] ,
127145 trigger : boolean | number ,
0 commit comments