Open History to see the last commit
1import type { RenderHookResult } from '@testing-library/react'
2
3/**
4 * React unmounts a root whose render throws without an error boundary, so a
5 * rejected reconfiguration leaves no binding to read. The returned guard runs
6 * a reconfiguration and records its rejection, whether `act` throws it or
7 * rejects with it. Every later result read rethrows that rejection instead of
8 * returning the unmounted hook's last committed value.
9 */
10export function rejectReadsAfterRenderError(
11 hook: RenderHookResult<any, any>,
12): <T>(reconfigure: () => T) => T {
13 let rejection: { error: unknown } | undefined
14 const result = hook.result
15 Object.defineProperty(hook, `result`, {
16 value: {
17 get current() {
18 if (rejection) throw rejection.error
19 return result.current
20 },
21 },
22 })
23 const record = (error: unknown): never => {
24 rejection ??= { error }
25 throw error
26 }
27 return (reconfigure) => {
28 try {
29 const value = reconfigure()
30 // React's async `act` returns a thenable, not a Promise.
31 return typeof (value as { then?: unknown } | null)?.then === `function`
32 ? (Promise.resolve(value).catch(record) as typeof value)
33 : value
34 } catch (error) {
35 return record(error)
36 }
37 }
38}