-
Notifications
You must be signed in to change notification settings - Fork 27
/
jest.setup.js
54 lines (49 loc) · 2.07 KB
/
jest.setup.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
import { configure } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import '@testing-library/jest-dom';
configure({ adapter: new Adapter() });
const observerMap = new Map();
const instanceMap = new Map();
beforeAll(() => {
// Stub `window.scroll` since Jest will fail otherwise. This may change in the future.
global.scroll = () => true;
// Some tests are run in the Jest `node` environment, where `window` is not defined, and these
// mocks are not needed.
if (typeof window !== 'undefined') {
// Mock `window.IntersectionObserver` using code from these two places:
// https://github.com/thebuilder/react-intersection-observer/blob/e31086c713615f3cfbe60eaa13491adcee3d41c2/src/test-utils.ts#L83
// https://jestjs.io/docs/en/manual-mocks#mocking-methods-which-are-not-implemented-in-jsdom
Object.defineProperty(window, 'IntersectionObserver', {
writable: true,
value: jest.fn((cb, options) => {
const instance = {
thresholds: Array.isArray(options.threshold)
? options.threshold
: [options.threshold],
root: options.root,
rootMargin: options.rootMargin,
time: Date.now(),
observe: jest.fn(element => {
instanceMap.set(element, instance);
observerMap.set(element, cb);
}),
unobserve: jest.fn(element => {
instanceMap.delete(element);
observerMap.delete(element);
}),
disconnect: jest.fn(),
};
return instance;
}),
});
}
});
afterEach(() => {
// Some tests are run in the Jest `node` environment, where `window` is not defined, and these
// mocks are not needed.
if (typeof window !== 'undefined') {
window.IntersectionObserver.mockClear();
instanceMap.clear();
observerMap.clear();
}
});