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

useStableCallback.browser.test.tsx

34 lines968 Bytes

1import { act } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4​
5import { useStableCallback } from "./useStableCallback";
6​
7let root: Root;
8let handlers: Array<() => string> = [];
9​
10function Probe({ label }: { label: string }) {
11 handlers.push(useStableCallback(() => label));
12 return null;
14​
15beforeEach(() => {
16 handlers = [];
17 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
18 root = createRoot(document.createElement("div"));
19});
20​
21afterEach(async () => {
22 await act(() => root.unmount());
23 vi.unstubAllGlobals();
24});
25​
26describe("useStableCallback", () => {
27 it("keeps one identity and calls the latest committed function", async () => {
28 await act(() => root.render(<Probe label="first" />));
29 await act(() => root.render(<Probe label="second" />));
30​
31 expect(new Set(handlers).size).toBe(1);
32 expect(handlers[0]!()).toBe("second");
33 });
34});