/
helpers.js
97 lines (85 loc) 路 2.55 KB
/
helpers.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
const globalObj = typeof window === 'undefined' ? global : window
// Currently this fn only supports jest timers, but it could support other test runners in the future.
function runWithRealTimers(callback) {
const usingJestFakeTimers =
globalObj.setTimeout &&
globalObj.setTimeout._isMockFunction &&
typeof jest !== 'undefined'
if (usingJestFakeTimers) {
jest.useRealTimers()
}
const callbackReturnValue = callback()
if (usingJestFakeTimers) {
jest.useFakeTimers()
}
return callbackReturnValue
}
// we only run our tests in node, and setImmediate is supported in node.
// istanbul ignore next
function setImmediatePolyfill(fn) {
return globalObj.setTimeout(fn, 0)
}
function getTimeFunctions() {
// istanbul ignore next
return {
clearTimeoutFn: globalObj.clearTimeout,
setImmediateFn: globalObj.setImmediate || setImmediatePolyfill,
setTimeoutFn: globalObj.setTimeout,
}
}
const {clearTimeoutFn, setImmediateFn, setTimeoutFn} = runWithRealTimers(
getTimeFunctions,
)
function getDocument() {
/* istanbul ignore if */
if (typeof window === 'undefined') {
throw new Error('Could not find default container')
}
return window.document
}
function getWindowFromNode(node) {
// istanbul ignore next I'm not sure what could cause the final else so we'll leave it uncovered.
if (node.defaultView) {
// node is document
return node.defaultView
} else if (node.ownerDocument && node.ownerDocument.defaultView) {
// node is a DOM node
return node.ownerDocument.defaultView
} else if (node.window) {
// node is window
return node.window
} else {
// no idea...
throw new Error(
`Unable to find the "window" object for the given node. Please file an issue with the code that's causing you to see this error: https://github.com/testing-library/dom-testing-library/issues/new`,
)
}
}
function checkContainerType(container) {
if (
!container ||
!(typeof container.querySelector === 'function') ||
!(typeof container.querySelectorAll === 'function')
) {
throw new TypeError(
`Expected container to be an Element, a Document or a DocumentFragment but got ${getTypeName(
container,
)}.`,
)
}
function getTypeName(object) {
if (typeof object === 'object') {
return object === null ? 'null' : object.constructor.name
}
return typeof object
}
}
export {
getWindowFromNode,
getDocument,
clearTimeoutFn as clearTimeout,
setImmediateFn as setImmediate,
setTimeoutFn as setTimeout,
runWithRealTimers,
checkContainerType,
}