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

closePreviewSession.test.ts

79 lines2.4 KB

1import type {
2 PreviewCloseInput,
3 PreviewSessionSnapshot,
4 ScopedThreadRef,
5} from "@t3tools/contracts";
6import * as Cause from "effect/Cause";
7import { AsyncResult } from "effect/unstable/reactivity";
8import { beforeEach, describe, expect, it, vi } from "vite-plus/test";
9​
10import {
11 applyPreviewServerSnapshot,
12 readThreadPreviewState,
13 resetPreviewStateForTests,
14} from "~/previewStateStore";
15​
16import { closePreviewSession } from "./closePreviewSession";
17​
18const threadRef = {
19 environmentId: "local" as ScopedThreadRef["environmentId"],
20 threadId: "thread-1" as ScopedThreadRef["threadId"],
21};
22​
23const snapshot: PreviewSessionSnapshot = {
24 threadId: threadRef.threadId,
25 tabId: "tab-1",
26 navStatus: {
27 _tag: "Success",
28 url: "http://localhost:3000/",
29 title: "Local app",
30 },
31 canGoBack: false,
32 canGoForward: false,
33 updatedAt: "2026-06-18T19:00:00.000Z",
34};
35​
36beforeEach(resetPreviewStateForTests);
37​
38describe("closePreviewSession", () => {
39 it("suppresses stale server snapshots while the close is in flight", async () => {
40 applyPreviewServerSnapshot(threadRef, snapshot);
41 let finishClose: (() => void) | undefined;
42 const closePreview = vi.fn(
43 (_input: PreviewCloseInput) =>
44 new Promise<ReturnType<typeof AsyncResult.success<void>>>((resolve) => {
45 finishClose = () => resolve(AsyncResult.success(undefined));
46 }),
47 );
48​
49 const closing = closePreviewSession({
50 closePreview: ({ input }) => closePreview(input),
51 snapshot,
52 tabId: snapshot.tabId,
53 threadRef,
54 });
55​
56 expect(readThreadPreviewState(threadRef).sessions).toEqual({});
57 applyPreviewServerSnapshot(threadRef, snapshot);
58 expect(readThreadPreviewState(threadRef).sessions).toEqual({});
59​
60 finishClose?.();
61 await closing;
62 expect(closePreview).toHaveBeenCalledWith({ threadId: "thread-1", tabId: "tab-1" });
63 });
64​
65 it("restores the last snapshot when the server close fails", async () => {
66 applyPreviewServerSnapshot(threadRef, snapshot);
67​
68 const result = await closePreviewSession({
69 closePreview: async () => AsyncResult.failure(Cause.fail(new Error("close failed"))),
70 snapshot,
71 tabId: snapshot.tabId,
72 threadRef,
73 });
74​
75 expect(result._tag).toBe("Failure");
76 expect(readThreadPreviewState(threadRef).snapshot).toEqual(snapshot);
77 expect(readThreadPreviewState(threadRef).sessions).toEqual({ [snapshot.tabId]: snapshot });
78 });
79});