Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

reactHookHarness.ts

62 lines1.9 KB

1import type { Dispatch, SetStateAction } from "react";
2​
3/**
4 * This module must stay free of runtime `react` imports: it is loaded from
5 * inside `vi.mock("react", ...)` factories, and a value import would recurse
6 * into the in-progress mock.
7 *
8 * Call `beginRender()` before each component invocation and `reset()` in
9 * `beforeEach` to drop persisted state between tests.
10 */
11function createReactHookHarness() {
12 let cursor = 0;
13 let slots: unknown[] = [];
14 const nextIndex = () => cursor++;
15​
16 return {
17 beginRender() {
18 cursor = 0;
19 },
20 reset() {
21 cursor = 0;
22 slots = [];
23 },
24 useCallback<T>(callback: T): T {
25 nextIndex();
26 return callback;
27 },
28 useMemo<T>(factory: () => T): T {
29 nextIndex();
30 return factory();
31 },
32 useMemoCache(size: number): unknown[] {
33 const index = nextIndex();
34 if (!slots[index]) {
35 slots[index] = Array.from({ length: size }, () => Symbol.for("react.memo_cache_sentinel"));
36 }
37 return slots[index] as unknown[];
38 },
39 useRef<T>(initialValue: T): { current: T } {
40 const index = nextIndex();
41 if (!slots[index]) {
42 slots[index] = { current: initialValue };
43 }
44 return slots[index] as { current: T };
45 },
46 useState<T>(initialValue: T | (() => T)): [T, Dispatch<SetStateAction<T>>] {
47 const index = nextIndex();
48 if (index >= slots.length) {
49 slots[index] =
50 typeof initialValue === "function" ? (initialValue as () => T)() : initialValue;
51 }
52 const setValue: Dispatch<SetStateAction<T>> = (nextValue) => {
53 const previous = slots[index] as T;
54 slots[index] =
55 typeof nextValue === "function" ? (nextValue as (value: T) => T)(previous) : nextValue;
56 };
57 return [slots[index] as T, setValue];
58 },
59 };
61​
62export const reactHookHarness = createReactHookHarness();