|
1 | 1 | import { afterEach, beforeEach, describe, expect, mock, test } from "bun:test"; |
2 | | -import { act, createElement } from "react"; |
| 2 | +import { StrictMode, act, createElement } from "react"; |
3 | 3 | import { createRoot } from "react-dom/client"; |
4 | 4 |
|
5 | 5 | import { |
6 | 6 | useControllableState, |
7 | 7 | type UseControllableStateOptions, |
8 | 8 | } from "./use-controllable-state.js"; |
| 9 | +import { renderHook } from "../test/render-hook.js"; |
9 | 10 |
|
10 | 11 | function mount<T>(options: UseControllableStateOptions<T>) { |
11 | 12 | const container = document.createElement("div"); |
@@ -52,6 +53,45 @@ describe("useControllableState", () => { |
52 | 53 | handle.unmount(); |
53 | 54 | }); |
54 | 55 |
|
| 56 | + test("uncontrolled: batched functional updates each see the previous result", () => { |
| 57 | + const changes: number[] = []; |
| 58 | + const { result, unmount } = renderHook(() => |
| 59 | + useControllableState({ |
| 60 | + defaultValue: 0, |
| 61 | + name: "test", |
| 62 | + onChange: (v) => changes.push(v), |
| 63 | + }), |
| 64 | + ); |
| 65 | + act(() => { |
| 66 | + result.current[1]((previous) => previous + 1); |
| 67 | + result.current[1]((previous) => previous + 1); |
| 68 | + }); |
| 69 | + expect(result.current[0]).toBe(2); |
| 70 | + expect(changes).toEqual([1, 2]); |
| 71 | + unmount(); |
| 72 | + }); |
| 73 | + |
| 74 | + test("uncontrolled: onChange fires once per update under StrictMode", () => { |
| 75 | + const changes: number[] = []; |
| 76 | + const container = document.createElement("div"); |
| 77 | + const root = createRoot(container); |
| 78 | + let set: ((action: (previous: number) => number) => void) | undefined; |
| 79 | + function Host() { |
| 80 | + set = useControllableState({ |
| 81 | + defaultValue: 0, |
| 82 | + name: "test", |
| 83 | + onChange: (v) => changes.push(v), |
| 84 | + })[1]; |
| 85 | + return null; |
| 86 | + } |
| 87 | + act(() => |
| 88 | + root.render(createElement(StrictMode, null, createElement(Host))), |
| 89 | + ); |
| 90 | + act(() => set?.((previous) => previous + 1)); |
| 91 | + expect(changes).toEqual([1]); |
| 92 | + act(() => root.unmount()); |
| 93 | + }); |
| 94 | + |
55 | 95 | test("controlled: the value tracks the prop, not internal state", () => { |
56 | 96 | let changed: boolean | undefined; |
57 | 97 | const handle = mount({ |
|
0 commit comments