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

useActiveThreadRef.browser.test.tsx

58 lines1.8 KB

1import type { EnvironmentId, ScopedThreadRef, ThreadId } from "@t3tools/contracts";
2import { act } from "react";
3import { createRoot, type Root } from "react-dom/client";
4import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
5​
6import { useActiveThreadRef } from "./useActiveThreadRef";
7​
8type ThreadLike = { environmentId: EnvironmentId; id: ThreadId; status: string } | null;
9​
10let root: Root;
11let observed: Array<ScopedThreadRef | null> = [];
12​
13function Probe({ thread }: { thread: ThreadLike }) {
14 observed.push(useActiveThreadRef(thread));
15 return null;
17​
18const thread = (id: string, status = "idle"): ThreadLike => ({
19 environmentId: "env-1" as EnvironmentId,
20 id: id as ThreadId,
21 status,
22});
23​
24async function render(value: ThreadLike) {
25 await act(() => root.render(<Probe thread={value} />));
26 return observed.at(-1);
28​
29beforeEach(() => {
30 observed = [];
31 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
32 root = createRoot(document.createElement("div"));
33});
34​
35afterEach(async () => {
36 await act(() => root.unmount());
37 vi.unstubAllGlobals();
38});
39​
40describe("useActiveThreadRef", () => {
41 it("keeps the same ref while the thread object is replaced during a run", async () => {
42 const first = await render(thread("t1", "running"));
43 const afterUpdate = await render(thread("t1", "waiting"));
44​
45 expect(first).toEqual({ environmentId: "env-1", threadId: "t1" });
46 expect(afterUpdate).toBe(first);
47 });
48​
49 it("returns a new ref when the thread changes or goes away", async () => {
50 const first = await render(thread("t1"));
51 const switched = await render(thread("t2"));
52 const gone = await render(null);
53​
54 expect(switched).not.toBe(first);
55 expect(switched).toEqual({ environmentId: "env-1", threadId: "t2" });
56 expect(gone).toBeNull();
57 });
58});