-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathhook-test-utils.ts
More file actions
99 lines (84 loc) · 2.36 KB
/
hook-test-utils.ts
File metadata and controls
99 lines (84 loc) · 2.36 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
import assert from 'node:assert/strict';
import {
QueryClient,
QueryClientProvider,
notifyManager,
} from '@tanstack/react-query';
import React from 'react';
import { act, create, type ReactTestRenderer } from 'react-test-renderer';
type WaitForOptions = {
timeoutMs?: number;
intervalMs?: number;
};
export interface HookHarness<TResult> {
getResult: () => TResult;
waitFor: (predicate: (result: TResult) => boolean, options?: WaitForOptions) => Promise<TResult>;
unmount: () => Promise<void>;
}
const DEFAULT_TIMEOUT_MS = 20_000;
const DEFAULT_INTERVAL_MS = 30;
let reactQueryActBridgeConfigured = false;
function sleep(ms: number): Promise<void> {
return new Promise((resolve) => {
setTimeout(resolve, ms);
});
}
export async function renderHookWithClient<TResult>(
useHook: () => TResult,
queryClient: QueryClient
): Promise<HookHarness<TResult>> {
(globalThis as { IS_REACT_ACT_ENVIRONMENT?: boolean }).IS_REACT_ACT_ENVIRONMENT = true;
if (!reactQueryActBridgeConfigured) {
notifyManager.setNotifyFunction((callback) => {
act(() => {
callback();
});
});
reactQueryActBridgeConfigured = true;
}
let renderer: ReactTestRenderer | null = null;
let latestResult: TResult | undefined;
function Probe(): null {
latestResult = useHook();
return null;
}
await act(async () => {
renderer = create(
React.createElement(
QueryClientProvider,
{ client: queryClient },
React.createElement(Probe, null)
)
);
});
function getResult(): TResult {
assert.notEqual(latestResult, undefined, 'Hook result is not ready yet');
return latestResult as TResult;
}
return {
getResult,
async waitFor(predicate, options) {
const timeoutMs = options?.timeoutMs ?? DEFAULT_TIMEOUT_MS;
const intervalMs = options?.intervalMs ?? DEFAULT_INTERVAL_MS;
const start = Date.now();
while (Date.now() - start < timeoutMs) {
const result = getResult();
if (predicate(result)) {
return result;
}
await act(async () => {
await sleep(intervalMs);
});
}
throw new Error(`Timed out waiting for hook condition after ${timeoutMs}ms`);
},
async unmount() {
if (!renderer) {
return;
}
await act(async () => {
renderer?.unmount();
});
},
};
}