@@ -9,25 +9,33 @@ type Item = {
99
1010const observers = new Map < IntersectionObserver , Item > ( ) ;
1111
12+ // Store a reference to the original `IntersectionObserver` so we can restore it later.
13+ // This can be relevant if testing in a browser environment, where you actually have a native `IntersectionObserver`.
14+ const originalIntersectionObserver =
15+ typeof window !== "undefined" ? window . IntersectionObserver : undefined ;
16+
17+ /**
18+ * Get the test utility object, depending on the environment. This could be either `vi` (Vitest) or `jest`.
19+ * Type is mapped to Vitest, so we don't mix in Jest types when running in Vitest.
20+ */
21+ function testLibraryUtil ( ) : typeof vi | undefined {
22+ if ( typeof vi !== "undefined" ) return vi ;
23+ // @ts -expect-error We don't include the Jest types
24+ if ( typeof jest !== "undefined" ) return jest ;
25+ return undefined ;
26+ }
27+
1228/**
1329 * Check if the IntersectionObserver is currently being mocked.
1430 * @return boolean
1531 */
16- const isMocking = ( ) => {
17- // @ts -ignore
18- if ( typeof jest !== "undefined" ) {
19- // @ts -ignore
20- return jest . isMockFunction ( window . IntersectionObserver ) ;
21- }
22- if ( typeof vi !== "undefined" ) {
23- return vi . isMockFunction ( window . IntersectionObserver ) ;
32+ function isMocking ( ) {
33+ const util = testLibraryUtil ( ) ;
34+ if ( util && typeof util . isMockFunction === "function" ) {
35+ return util . isMockFunction ( window . IntersectionObserver ) ;
2436 }
25- } ;
26-
27- // Store a reference to the original `IntersectionObserver` so we can restore it later.
28- // This can be relevant if testing in a browser environment, where you actually have a native `IntersectionObserver`.
29- const originalIntersectionObserver =
30- typeof window !== "undefined" ? window . IntersectionObserver : undefined ;
37+ return false ;
38+ }
3139
3240/*
3341 ** If we are running in a valid testing environment, we can automate mocking the IntersectionObserver.
3846 typeof afterEach !== "undefined"
3947) {
4048 beforeEach ( ( ) => {
41- // Use the exposed mock function. Currently, it supports Jest (`jest.fn`) and Vitest with globals (`vi.fn`).
42- // @ts -ignore
43- if ( typeof jest !== "undefined" ) setupIntersectionMocking ( jest . fn ) ;
44- else if ( typeof vi !== "undefined" ) {
45- setupIntersectionMocking ( vi . fn ) ;
49+ const util = testLibraryUtil ( ) ;
50+ if ( util ) {
51+ setupIntersectionMocking ( util . fn ) ;
4652 }
4753 // Ensure there's no observers from previous tests
4854 observers . clear ( ) ;
0 commit comments