-
Notifications
You must be signed in to change notification settings - Fork 0
/
testdom.js
104 lines (89 loc) · 2.38 KB
/
testdom.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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
/**
* Copyright (c) 2016 - 2024 Alex Grant (@localnerve), LocalNerve LLC
* Copyrights licensed under the BSD License. See the accompanying LICENSE file for terms.
*
* Start/stop jsdom environment
*/
/* global document */
import { JSDOM } from 'jsdom';
/**
* Wrap the JSDOM api.
*
* @param {String} markup - The markup to init JSDOM with.
* @param {Object} options - The options to init JSDOM with.
* @returns {Object} window, document, and navigator as { win, doc, nav }.
*/
function createJSDOM (markup, options) {
const dom = new JSDOM(markup, options);
return {
win: dom.window,
doc: dom.window.document,
nav: dom.window.navigator
};
}
/**
* Shim document, window, and navigator with jsdom if not defined.
* Init document with markup if specified.
* Add globals if specified.
*/
export function domStart (markup, addGlobals) {
if (typeof document !== 'undefined') {
return;
}
const globalKeys = [];
const { win, doc, nav } = createJSDOM(
markup || '<!doctype html><html><body></body></html>'
);
global.IS_REACT_ACT_ENVIRONMENT = true;
global.document = doc;
global.window = win;
global.navigator = nav;
if (addGlobals) {
Object.keys(addGlobals).forEach(function (key) {
global.window[key] = addGlobals[key];
globalKeys.push(key);
});
}
return globalKeys;
}
/**
* Remove globals, stop and delete the window.
*/
export function domStop (globalKeys) {
if (globalKeys) {
globalKeys.forEach(function (key) {
delete global.window[key];
});
}
global.window.close();
delete global.document;
delete global.window;
delete global.navigator;
}
const savedItems = {
window: {
},
document: {
}
};
/**
* patch document and window for the component under test
*
* @returns {Object} contains relevant dom properties to the calling test.
*/
export function mockStart (patch) {
savedItems.window.pageYOffset = global.window.pageYOffset;
savedItems.document.querySelector = global.document.querySelector;
global.window.pageYOffset = patch.pageYOffset;
global.document.querySelector = patch.querySelector;
return {
clientTop: global.document.documentElement.clientTop
};
}
/**
* restore document and window for the component under test
*/
export function mockEnd () {
global.window.pageYOffset = savedItems.window.pageYOffset;
global.document.querySelector = savedItems.document.querySelector;
}