Skip to content

Commit 189133f

Browse files
committed
fix: use isMockFunction to detect if the IntersectionObserver is being mocked
1 parent f098c1e commit 189133f

File tree

1 file changed

+17
-7
lines changed

1 file changed

+17
-7
lines changed

src/test-utils.ts

+17-7
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,23 @@ type Item = {
77
created: number;
88
};
99

10-
let isMocking = false;
11-
1210
const observers = new Map<IntersectionObserver, Item>();
1311

12+
/**
13+
* Check if the IntersectionObserver is currently being mocked.
14+
* @return boolean
15+
*/
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);
24+
}
25+
};
26+
1427
// Store a reference to the original `IntersectionObserver` so we can restore it later.
1528
// This can be relevant if testing in a browser environment, where you actually have a native `IntersectionObserver`.
1629
const originalIntersectionObserver =
@@ -57,7 +70,7 @@ function getActFn() {
5770
}
5871

5972
function warnOnMissingSetup() {
60-
if (isMocking) return;
73+
if (isMocking()) return;
6174
console.error(
6275
`React Intersection Observer was not configured to handle mocking.
6376
Outside Jest and Vitest, you might need to manually configure it by calling setupIntersectionMocking() and resetIntersectionMocking() in your test setup file.
@@ -82,7 +95,7 @@ afterEach(() => {
8295
* @param mockFn The mock function to use. Defaults to `vi.fn`.
8396
*/
8497
export function setupIntersectionMocking(mockFn: typeof vi.fn) {
85-
if (isMocking) return;
98+
if (isMocking()) return;
8699
window.IntersectionObserver = mockFn((cb, options = {}) => {
87100
const item = {
88101
callback: cb,
@@ -111,8 +124,6 @@ export function setupIntersectionMocking(mockFn: typeof vi.fn) {
111124

112125
return instance;
113126
});
114-
115-
isMocking = true;
116127
}
117128

118129
/**
@@ -137,7 +148,6 @@ export function destroyIntersectionMocking() {
137148
resetIntersectionMocking();
138149
// @ts-ignore
139150
window.IntersectionObserver = originalIntersectionObserver;
140-
isMocking = false;
141151
}
142152

143153
function triggerIntersection(

0 commit comments

Comments
 (0)