Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

_helpers.ts

94 lines2.8 KB

1/**
2 * Test helpers β€” thin wrapper around createRoot + flushSync so tests can
3 * mount a component, inspect the DOM, fire events, and unmount cleanly.
4 */
5import {
6 createRoot,
7 delegateEvents,
8 drainPassiveEffects,
9 flushSync,
10} from 'octane'
11import type { ComponentBody, Root } from 'octane'
12​
13// Delegated events used by test fixtures. Setup-once.
14delegateEvents(['click', 'input', 'change', 'keydown', 'submit'])
15​
16interface MountResult {
17 container: HTMLElement
18 root: Root
19 html: () => string
20 unmount: () => void
21 click: (selector: string) => void
22 find: (selector: string) => Element
23 findAll: (selector: string) => Array<Element>
24 /** Re-render with new props (drains queued renders synchronously). */
25 update: <TProps>(body: ComponentBody<TProps>, props?: TProps) => void
27​
28export function mount<TProps = undefined>(
29 body: ComponentBody<TProps>,
30 props?: TProps,
31): MountResult {
32 const container = document.createElement('div')
33 document.body.appendChild(container)
34 const root = createRoot(container)
35 try {
36 root.render(body, props)
37 flushSync(() => {})
38 } catch (err) {
39 // A throwing initial render can't be unmounted by the caller because mount
40 // never returns. Release the root's delegation/ownership registrations as
41 // well as its container before preserving the original render error.
42 try {
43 root.unmount()
44 } finally {
45 container.remove()
46 }
47 throw err
48 }
49 return {
50 container,
51 root,
52 html() {
53 return container.innerHTML
54 },
55 unmount() {
56 root.unmount()
57 container.remove()
58 },
59 click(selector) {
60 const el = container.querySelector(selector)
61 if (!el) throw new Error(`no element matching ${selector}`)
62 flushSync(() => {
63 // HTMLElement has `.click()`. SVGElement / MathMLElement do NOT
64 // (they're not in the HTMLElement prototype chain), so we dispatch
65 // a bubbling click event explicitly β€” matches the real browser path
66 // the runtime listens on at the delegation root.
67 if (typeof (el as HTMLElement).click === 'function') {
68 ;(el as HTMLElement).click()
69 } else {
70 el.dispatchEvent(
71 new MouseEvent('click', { bubbles: true, cancelable: true }),
72 )
73 }
74 })
75 },
76 find(selector) {
77 const el = container.querySelector(selector)
78 if (!el) throw new Error(`no element matching ${selector}`)
79 return el
80 },
81 findAll(selector) {
82 return Array.from(container.querySelectorAll(selector))
83 },
84 update(nextBody, nextProps) {
85 flushSync(() => root.render(nextBody, nextProps))
86 },
87 }
89​
90/** Older name kept for tests that read more naturally with it. */
91export function nextPaint(): Promise<void> {
92 drainPassiveEffects()
93 return Promise.resolve()