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

fileSaveSessions.browser.test.tsx

83 lines2.8 KB

1import { render, fakeTimers } from "../../../test/render";
2import { EnvironmentId } from "@t3tools/contracts";
3import { AsyncResult } from "effect/reactivity";
4import { StrictMode } from "react";
5import { describe, expect, it, vi } from "vite-plus/test";
6​
7const { runAtomCommand, getUnsavedFile } = vi.hoisted(() => ({
8 runAtomCommand: vi.fn(),
9 getUnsavedFile: vi.fn(),
10}));
11vi.mock(import("@t3tools/client-runtime/state/runtime"), async (original) => ({
12 ...(await original()),
13 runAtomCommand: runAtomCommand as never,
14}));
15vi.mock(import("~/state/session"), async (original) => ({
16 ...(await original()),
17 readEnvironmentScope: () => true,
18}));
19vi.mock(import("./projectFilesQueryState"), async (original) => ({
20 ...(await original()),
21 confirmProjectFileQueryData: () => true,
22 getUnsavedProjectFileQueryData: getUnsavedFile,
23}));
24​
25import { changeFileSaveSession, useFileSaveSession } from "./fileSaveSessions";
26​
27const target = {
28 environmentId: EnvironmentId.make("file-save-sessions-browser"),
29 cwd: "/workspace",
30 relativePath: "README.md",
31};
32const onPendingChange = vi.fn();
33​
34// The editor and rendered-markdown surfaces are different component types, so
35// switching between them unmounts one session holder and mounts another.
36function EditorSurface() {
37 useFileSaveSession({ ...target }, onPendingChange);
38 return <div>editor</div>;
40function MarkdownSurface() {
41 useFileSaveSession({ ...target }, onPendingChange);
42 return <div>markdown</div>;
44​
45describe("file save sessions in React", () => {
46 it("writes a pending draft once when the file switches surfaces under StrictMode", async () => {
47 let finishWrite = () => {};
48 runAtomCommand.mockReset().mockImplementation(
49 () =>
50 new Promise((resolve) => {
51 finishWrite = () => resolve(AsyncResult.success(undefined));
52 }),
53 );
54 getUnsavedFile.mockReset().mockReturnValue(null);
55 await using screen = await render(
56 <StrictMode>
57 <EditorSurface />
58 </StrictMode>,
59 { router: false }, // no routes involved; the surfaces are bare effect hosts
60 );
61 using _timers = fakeTimers();
62 // An edit lands in the query cache, unconfirmed until its write settles.
63 getUnsavedFile.mockReturnValue({ contents: "draft" });
64 changeFileSaveSession(target, "draft");
65​
66 await screen.rerender(
67 <StrictMode>
68 <MarkdownSurface />
69 </StrictMode>,
70 );
71 finishWrite();
72 getUnsavedFile.mockReturnValue(null);
73 await vi.runAllTimersAsync();
74​
75 expect(runAtomCommand.mock.calls.map(([, , request]) => request)).toEqual([
76 {
77 environmentId: target.environmentId,
78 input: { cwd: "/workspace", relativePath: "README.md", contents: "draft" },
79 },
80 ]);
81 expect(onPendingChange).toHaveBeenLastCalledWith("README.md", false);
82 });
83});