@@ -9,25 +9,33 @@ type Item = {
9
9
10
10
const observers = new Map < IntersectionObserver , Item > ( ) ;
11
11
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
+
12
28
/**
13
29
* Check if the IntersectionObserver is currently being mocked.
14
30
* @return boolean
15
31
*/
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 ) ;
24
36
}
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
+ }
31
39
32
40
/*
33
41
** If we are running in a valid testing environment, we can automate mocking the IntersectionObserver.
38
46
typeof afterEach !== "undefined"
39
47
) {
40
48
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 ) ;
46
52
}
47
53
// Ensure there's no observers from previous tests
48
54
observers . clear ( ) ;
0 commit comments