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

panelAnimations.browser.test.tsx

61 lines1.9 KB

1import { act, useLayoutEffect } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4​
5import { usePanelNavigationSuppression } from "./panelAnimations";
6​
7let root: Root;
8let pendingFrames: FrameRequestCallback[] = [];
9let observed: boolean[] = [];
10​
11function SuppressionProbe({ navigationKey }: { navigationKey: string }) {
12 const suppressed = usePanelNavigationSuppression(navigationKey);
13 useLayoutEffect(() => {
14 observed.push(suppressed);
15 }, [suppressed]);
16 return null;
18​
19beforeEach(() => {
20 pendingFrames = [];
21 observed = [];
22 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
23 // Frames are stepped by hand so each assertion lands between two paints.
24 vi.spyOn(window, "requestAnimationFrame").mockImplementation((callback) => {
25 pendingFrames.push(callback);
26 return pendingFrames.length;
27 });
28 vi.spyOn(window, "cancelAnimationFrame").mockImplementation(() => undefined);
29 root = createRoot(document.createElement("div"));
30});
31​
32afterEach(async () => {
33 await act(() => root.unmount());
34 vi.restoreAllMocks();
35 vi.unstubAllGlobals();
36});
37​
38async function paintPendingFrame() {
39 const callback = pendingFrames.shift();
40 await act(() => callback?.(0));
42​
43describe("usePanelNavigationSuppression", () => {
44 it("suppresses initial and navigated panel state until each route has painted", async () => {
45 await act(() => root.render(<SuppressionProbe navigationKey="/thread/one" />));
46 expect(observed.at(-1)).toBe(true);
47​
48 await paintPendingFrame();
49 expect(observed.at(-1)).toBe(true);
50 await paintPendingFrame();
51 expect(observed.at(-1)).toBe(false);
52​
53 await act(() => root.render(<SuppressionProbe navigationKey="/thread/two" />));
54 expect(observed.at(-1)).toBe(true);
55​
56 await paintPendingFrame();
57 expect(observed.at(-1)).toBe(true);
58 await paintPendingFrame();
59 expect(observed.at(-1)).toBe(false);
60 });
61});