forked from testing-library/react-testing-library
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
60 lines (52 loc) · 2.15 KB
/
index.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
import ReactDOM from 'react-dom'
import {Simulate} from 'react-dom/test-utils'
import {getQueriesForElement, prettyDOM} from 'dom-testing-library'
const mountedContainers = new Set()
function render(ui, {container, baseElement = container, queries} = {}) {
if (!container) {
// default to document.body instead of documentElement to avoid output of potentially-large
// head elements (such as JSS style blocks) in debug output
baseElement = document.body
container = document.body.appendChild(document.createElement('div'))
}
// we'll add it to the mounted containers regardless of whether it's actually
// added to document.body so the cleanup method works regardless of whether
// they're passing us a custom container or not.
mountedContainers.add(container)
ReactDOM.render(ui, container)
return {
container,
baseElement,
// eslint-disable-next-line no-console
debug: (el = baseElement) => console.log(prettyDOM(el)),
unmount: () => ReactDOM.unmountComponentAtNode(container),
rerender: rerenderUi => {
render(rerenderUi, {container, baseElement})
// Intentionally do not return anything to avoid unnecessarily complicating the API.
// folks can use all the same utilities we return in the first place that are bound to the container
},
...getQueriesForElement(baseElement, queries),
}
}
function cleanup() {
mountedContainers.forEach(cleanupAtContainer)
}
// maybe one day we'll expose this (perhaps even as a utility returned by render).
// but let's wait until someone asks for it.
function cleanupAtContainer(container) {
if (container.parentNode === document.body) {
document.body.removeChild(container)
}
ReactDOM.unmountComponentAtNode(container)
mountedContainers.delete(container)
}
// fallback to synthetic events for React events that the DOM doesn't support
const syntheticEvents = ['select', 'mouseEnter', 'mouseLeave']
syntheticEvents.forEach(eventName => {
document.addEventListener(eventName.toLowerCase(), e => {
Simulate[eventName](e.target, e)
})
})
// just re-export everything from dom-testing-library
export * from 'dom-testing-library'
export {render, cleanup}