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

CdpRelay.test.ts

192 lines7.3 KB

1import { describe, expect, it, vi } from "vite-plus/test";
2​
3import { createCdpRelayConnection, type CdpRelayTarget } from "./CdpRelay.ts";
4​
5const makeTarget = (
6 send: CdpRelayTarget["send"],
7 setDownloadDirectory: CdpRelayTarget["setDownloadDirectory"] = () => {},
8): CdpRelayTarget => ({
9 send,
10 targetId: async () => "GUEST-TARGET",
11 url: () => "http://localhost:4719/",
12 title: () => "Fixture",
13 userAgent: () => "Electron",
14 setDownloadDirectory,
15});
16​
17// Each relay reply resolves after a few microtasks; one macrotask lets them all land.
18// oxlint-disable-next-line t3code/no-real-time-wait-in-tests -- a zero-delay macrotask boundary, not a wait for time
19const settle = () => new Promise<void>((resolve) => setImmediate(resolve));
20​
21describe("CDP relay", () => {
22 it("announces only the tab's page, under its real target id", async () => {
23 const written: Array<Record<string, unknown>> = [];
24 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
25 written.push(JSON.parse(raw)),
26 );
27 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
28 relay.receive(JSON.stringify({ id: 2, method: "Target.createTarget", params: {} }));
29 await settle();
30 const attach = written.findIndex((message) => message["id"] === 1);
31 expect(written.slice(attach, attach + 2)).toEqual([
32 { id: 1, result: {} },
33 {
34 method: "Target.attachedToTarget",
35 params: expect.objectContaining({
36 sessionId: "t3-preview-page",
37 targetInfo: expect.objectContaining({ targetId: "GUEST-TARGET", type: "page" }),
38 }),
39 },
40 ]);
41 expect(written).toContainEqual({
42 id: 2,
43 error: expect.objectContaining({ message: expect.stringContaining("createTarget") }),
44 });
45 });
46​
47 it("forwards page commands to the tab and lets a slow one finish last", async () => {
48 const pending: Array<() => void> = [];
49 const send = vi.fn(
50 (method: string) =>
51 new Promise<unknown>((resolve) => pending.push(() => resolve({ method }))),
52 );
53 const written: Array<Record<string, unknown>> = [];
54 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
55 written.push(JSON.parse(raw)),
56 );
57 relay.receive(
58 JSON.stringify({ id: 5, method: "Page.captureScreenshot", sessionId: "t3-preview-page" }),
59 );
60 relay.receive(JSON.stringify({ id: 6, method: "DOM.enable", sessionId: "iframe-session" }));
61 pending[1]!();
62 await settle();
63 expect(written).toEqual([
64 { id: 6, result: { method: "DOM.enable" }, sessionId: "iframe-session" },
65 ]);
66 pending[0]!();
67 await settle();
68 expect(send).toHaveBeenNthCalledWith(1, "Page.captureScreenshot", {}, undefined);
69 expect(send).toHaveBeenNthCalledWith(2, "DOM.enable", {}, "iframe-session");
70 expect(written.at(-1)).toEqual({
71 id: 5,
72 result: { method: "Page.captureScreenshot" },
73 sessionId: "t3-preview-page",
74 });
75 });
76​
77 it("resumes paused child frames, so cross-site iframes run", async () => {
78 const send = vi.fn(async () => ({}));
79 const relay = createCdpRelayConnection(makeTarget(send), () => {});
80 relay.receive(
81 JSON.stringify({
82 id: 1,
83 method: "Runtime.runIfWaitingForDebugger",
84 sessionId: "t3-preview-page",
85 }),
86 );
87 relay.receive(
88 JSON.stringify({
89 id: 2,
90 method: "Runtime.runIfWaitingForDebugger",
91 sessionId: "iframe-session",
92 }),
93 );
94 await settle();
95 expect(send.mock.calls).toEqual([["Runtime.runIfWaitingForDebugger", {}, "iframe-session"]]);
96 });
97​
98 it("routes tab events to the page session once the page is announced", async () => {
99 const written: Array<Record<string, unknown>> = [];
100 const relay = createCdpRelayConnection(makeTarget(vi.fn()), (raw) =>
101 written.push(JSON.parse(raw)),
102 );
103 relay.event("Page.loadEventFired", {}, undefined);
104 expect(written).toEqual([]);
105 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
106 await settle();
107 relay.event("Page.loadEventFired", { timestamp: 1 }, "");
108 relay.event("Runtime.consoleAPICalled", {}, "iframe-session");
109 expect(written.slice(-2)).toEqual([
110 { method: "Page.loadEventFired", params: { timestamp: 1 }, sessionId: "t3-preview-page" },
111 { method: "Runtime.consoleAPICalled", params: {}, sessionId: "iframe-session" },
112 ]);
113 });
114});
115​
116describe("CDP relay extra sessions", () => {
117 it("gives a second page session the page's commands and events", async () => {
118 const send = vi.fn(async () => ({}));
119 const written: Array<Record<string, unknown>> = [];
120 const relay = createCdpRelayConnection(makeTarget(send), (raw) =>
121 written.push(JSON.parse(raw)),
122 );
123 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
124 relay.receive(JSON.stringify({ id: 2, method: "Target.attachToBrowserTarget" }));
125 await settle();
126 const browserSession = (written.find((m) => m["id"] === 2)!["result"] as { sessionId: string })
127 .sessionId;
128 relay.receive(
129 JSON.stringify({
130 id: 3,
131 method: "Target.attachToTarget",
132 params: { targetId: "GUEST-TARGET", flatten: true },
133 sessionId: browserSession,
134 }),
135 );
136 relay.receive(
137 JSON.stringify({
138 id: 4,
139 method: "Target.attachToTarget",
140 params: { targetId: "SOMETHING-ELSE" },
141 sessionId: browserSession,
142 }),
143 );
144 await settle();
145 const extra = (written.find((m) => m["id"] === 3)!["result"] as { sessionId: string })
146 .sessionId;
147 expect(written.find((m) => m["id"] === 4)).toHaveProperty("error");
148 relay.receive(JSON.stringify({ id: 5, method: "Page.startScreencast", sessionId: extra }));
149 await settle();
150 expect(send).toHaveBeenLastCalledWith("Page.startScreencast", {}, undefined);
151 written.length = 0;
152 relay.event("Page.screencastFrame", { data: "x" }, undefined);
153 expect(written.map((m) => m["sessionId"])).toEqual(["t3-preview-page", extra]);
154 });
155});
156​
157describe("CDP relay downloads", () => {
158 it("applies the server's download directory and reports downloads on the root session", async () => {
159 const send = vi.fn(async () => ({}));
160 const directories: Array<string | null> = [];
161 const written: Array<Record<string, unknown>> = [];
162 const relay = createCdpRelayConnection(
163 makeTarget(send, (directory) => directories.push(directory)),
164 (raw) => written.push(JSON.parse(raw)),
165 );
166 relay.receive(JSON.stringify({ id: 1, method: "Target.setAutoAttach", params: {} }));
167 relay.receive(
168 JSON.stringify({
169 id: 2,
170 method: "Browser.setDownloadBehavior",
171 params: {
172 behavior: "allowAndName",
173 browserContextId: "t3-preview",
174 downloadPath: "/srv/artifacts",
175 eventsEnabled: true,
176 },
177 }),
178 );
179 await settle();
180 expect(directories).toEqual(["/srv/artifacts"]);
181 expect(send).toHaveBeenCalledWith(
182 "Browser.setDownloadBehavior",
183 { behavior: "allowAndName", downloadPath: "/srv/artifacts", eventsEnabled: true },
184 undefined,
185 );
186 written.length = 0;
187 relay.event("Browser.downloadWillBegin", { guid: "g1", suggestedFilename: "r.csv" }, "");
188 expect(written).toEqual([
189 { method: "Browser.downloadWillBegin", params: { guid: "g1", suggestedFilename: "r.csv" } },
190 ]);
191 });
192});