forked from vitest-community/vitest-browser-react
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpure.tsx
More file actions
262 lines (225 loc) · 7.49 KB
/
pure.tsx
File metadata and controls
262 lines (225 loc) · 7.49 KB
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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
import type { Locator, LocatorSelectors, PrettyDOMOptions } from 'vitest/browser'
import { page, server, utils } from 'vitest/browser'
import React from 'react'
import type { Container } from 'react-dom/client'
import ReactDOMClient from 'react-dom/client'
import { nanoid } from '@vitest/utils/helpers'
const { debug, getElementLocatorSelectors } = utils
function getTestIdAttribute() {
return server.config.browser.locators.testIdAttribute
}
let activeActs = 0
function setActEnvironment(env: boolean | undefined): void {
(globalThis as any).IS_REACT_ACT_ENVIRONMENT = env
}
function updateActEnvironment(): void {
setActEnvironment(activeActs > 0)
}
// @ts-expect-error unstable_act is not typed, but exported
const _act = React.act || React.unstable_act
// we call act only when rendering to flush any possible effects
// usually the async nature of Vitest browser mode ensures consistency,
// but rendering is sync and controlled by React directly
const act = typeof _act !== 'function'
? async (cb: () => unknown) => { await cb() }
: async (cb: () => unknown) => {
activeActs++
updateActEnvironment()
try {
await _act(cb)
}
finally {
activeActs--
updateActEnvironment()
}
}
export interface RenderResult extends LocatorSelectors {
container: HTMLElement
baseElement: HTMLElement
locator: Locator
debug: (
el?: HTMLElement | HTMLElement[] | Locator | Locator[],
maxLength?: number,
options?: PrettyDOMOptions
) => void
unmount: () => Promise<void>
rerender: (ui: React.ReactNode) => Promise<void>
asFragment: () => DocumentFragment
}
export interface ComponentRenderOptions {
container?: HTMLElement
baseElement?: HTMLElement
wrapper?: React.JSXElementConstructor<{ children: React.ReactNode }>
}
export interface RenderOptions extends ComponentRenderOptions {}
// Ideally we'd just use a WeakMap where containers are keys and roots are values.
// We use two variables so that we can bail out in constant time when we render with a new container (most common use case)
const mountedContainers = new Set<Container>()
const mountedRootEntries: {
container: Container
root: ReturnType<typeof createConcurrentRoot>
}[] = []
export async function render(
ui: React.ReactNode,
{ container, baseElement, wrapper: WrapperComponent }: ComponentRenderOptions = {},
): Promise<RenderResult> {
if (!baseElement) {
// 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
if (!document.body.hasAttribute(getTestIdAttribute())) {
document.body.setAttribute(getTestIdAttribute(), nanoid())
}
}
if (!container) {
container = baseElement.appendChild(document.createElement('div'))
container.setAttribute(getTestIdAttribute(), nanoid())
}
let root: ReactRoot
if (!mountedContainers.has(container)) {
root = createConcurrentRoot(container)
mountedRootEntries.push({ container, root })
// 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)
}
else {
mountedRootEntries.forEach((rootEntry) => {
// Else is unreachable since `mountedContainers` has the `container`.
// Only reachable if one would accidentally add the container to `mountedContainers` but not the root to `mountedRootEntries`
/* istanbul ignore else */
if (rootEntry.container === container) {
root = rootEntry.root
}
})
}
await act(() => {
root!.render(
strictModeIfNeeded(wrapUiIfNeeded(ui, WrapperComponent)),
)
})
return {
container,
baseElement,
locator: page.elementLocator(container),
debug: (el, maxLength, options) => debug(el, maxLength, options),
unmount: async () => {
await act(() => {
root.unmount()
})
},
rerender: async (newUi: React.ReactNode) => {
await act(() => {
root.render(
strictModeIfNeeded(wrapUiIfNeeded(newUi, WrapperComponent)),
)
})
},
asFragment: () => {
return document.createRange().createContextualFragment(container.innerHTML)
},
...getElementLocatorSelectors(baseElement),
}
}
export interface RenderHookOptions<Props> extends ComponentRenderOptions {
/**
* The argument passed to the renderHook callback. Can be useful if you plan
* to use the rerender utility to change the values passed to your hook.
*/
initialProps?: Props | undefined
}
export interface RenderHookResult<Result, Props> {
/**
* Triggers a re-render. The props will be passed to your renderHook callback.
*/
rerender: (props?: Props) => Promise<void>
/**
* This is a stable reference to the latest value returned by your renderHook
* callback
*/
result: {
/**
* The value returned by your renderHook callback
*/
current: Result
}
/**
* Unmounts the test component. This is useful for when you need to test
* any cleanup your useEffects have.
*/
unmount: () => Promise<void>
/**
* A test helper to apply pending React updates before making assertions.
*/
act: (callback: () => unknown) => Promise<void>
}
export async function renderHook<Props, Result>(renderCallback: (initialProps?: Props) => Result, options: RenderHookOptions<Props> = {}): Promise<RenderHookResult<Result, Props>> {
const { initialProps, ...renderOptions } = options
const result = React.createRef<Result>() as unknown as { current: Result }
function TestComponent({ renderCallbackProps }: { renderCallbackProps?: Props }) {
const pendingResult = renderCallback(renderCallbackProps)
React.useEffect(() => {
result.current = pendingResult
})
return null
}
const { rerender: baseRerender, unmount } = await render(
<TestComponent renderCallbackProps={initialProps} />,
renderOptions,
)
function rerender(rerenderCallbackProps?: Props) {
return baseRerender(
<TestComponent renderCallbackProps={rerenderCallbackProps} />,
)
}
return { result, rerender, unmount, act }
}
export async function cleanup(): Promise<void> {
for (const { root, container } of mountedRootEntries) {
await act(() => {
root.unmount()
})
if (container.parentNode === document.body) {
document.body.removeChild(container)
}
}
mountedRootEntries.length = 0
mountedContainers.clear()
}
interface ReactRoot {
render: (element: React.ReactNode) => void
unmount: () => void
}
function createConcurrentRoot(container: HTMLElement): ReactRoot {
const root = ReactDOMClient.createRoot(container)
return {
render(element: React.ReactNode) {
root.render(element)
},
unmount() {
root.unmount()
},
}
}
export interface RenderConfiguration {
reactStrictMode: boolean
}
const config: RenderConfiguration = {
reactStrictMode: false,
}
function strictModeIfNeeded(innerElement: React.ReactNode) {
return config.reactStrictMode
? React.createElement(React.StrictMode, null, innerElement)
: innerElement
}
function wrapUiIfNeeded(innerElement: React.ReactNode, wrapperComponent?: React.JSXElementConstructor<{
children: React.ReactNode
}>) {
return wrapperComponent
? React.createElement(wrapperComponent, null, innerElement)
: innerElement
}
export function configure(customConfig: Partial<RenderConfiguration>): void {
Object.assign(config, customConfig)
}