test(browser): dedupe CDP and download setup helpers

This commit is contained in:
Peter Steinberger
2026-02-19 07:23:44 +00:00
parent 192366e0e8
commit c085c9e6d0
2 changed files with 98 additions and 115 deletions

View File

@@ -1,6 +1,6 @@
import { createServer } from "node:http"; import { createServer } from "node:http";
import { afterEach, describe, expect, it } from "vitest"; import { afterEach, describe, expect, it } from "vitest";
import { WebSocketServer } from "ws"; import { type WebSocket, WebSocketServer } from "ws";
import { rawDataToString } from "../infra/ws.js"; import { rawDataToString } from "../infra/ws.js";
import { createTargetViaCdp, evaluateJavaScript, normalizeCdpWsUrl, snapshotAria } from "./cdp.js"; import { createTargetViaCdp, evaluateJavaScript, normalizeCdpWsUrl, snapshotAria } from "./cdp.js";
@@ -14,6 +14,29 @@ describe("cdp", () => {
return (wsServer.address() as { port: number }).port; return (wsServer.address() as { port: number }).port;
}; };
const startWsServerWithMessages = async (
onMessage: (
msg: { id?: number; method?: string; params?: Record<string, unknown> },
socket: WebSocket,
) => void,
) => {
const wsPort = await startWsServer();
if (!wsServer) {
throw new Error("ws server not initialized");
}
wsServer.on("connection", (socket) => {
socket.on("message", (data) => {
const msg = JSON.parse(rawDataToString(data)) as {
id?: number;
method?: string;
params?: Record<string, unknown>;
};
onMessage(msg, socket);
});
});
return wsPort;
};
afterEach(async () => { afterEach(async () => {
await new Promise<void>((resolve) => { await new Promise<void>((resolve) => {
if (!httpServer) { if (!httpServer) {
@@ -32,28 +55,16 @@ describe("cdp", () => {
}); });
it("creates a target via the browser websocket", async () => { it("creates a target via the browser websocket", async () => {
const wsPort = await startWsServer(); const wsPort = await startWsServerWithMessages((msg, socket) => {
if (!wsServer) { if (msg.method !== "Target.createTarget") {
throw new Error("ws server not initialized"); return;
} }
socket.send(
wsServer.on("connection", (socket) => { JSON.stringify({
socket.on("message", (data) => { id: msg.id,
const msg = JSON.parse(rawDataToString(data)) as { result: { targetId: "TARGET_123" },
id?: number; }),
method?: string; );
params?: { url?: string };
};
if (msg.method !== "Target.createTarget") {
return;
}
socket.send(
JSON.stringify({
id: msg.id,
result: { targetId: "TARGET_123" },
}),
);
});
}); });
httpServer = createServer((req, res) => { httpServer = createServer((req, res) => {
@@ -82,32 +93,20 @@ describe("cdp", () => {
}); });
it("evaluates javascript via CDP", async () => { it("evaluates javascript via CDP", async () => {
const wsPort = await startWsServer(); const wsPort = await startWsServerWithMessages((msg, socket) => {
if (!wsServer) { if (msg.method === "Runtime.enable") {
throw new Error("ws server not initialized"); socket.send(JSON.stringify({ id: msg.id, result: {} }));
} return;
}
wsServer.on("connection", (socket) => { if (msg.method === "Runtime.evaluate") {
socket.on("message", (data) => { expect(msg.params?.expression).toBe("1+1");
const msg = JSON.parse(rawDataToString(data)) as { socket.send(
id?: number; JSON.stringify({
method?: string; id: msg.id,
params?: { expression?: string }; result: { result: { type: "number", value: 2 } },
}; }),
if (msg.method === "Runtime.enable") { );
socket.send(JSON.stringify({ id: msg.id, result: {} })); }
return;
}
if (msg.method === "Runtime.evaluate") {
expect(msg.params?.expression).toBe("1+1");
socket.send(
JSON.stringify({
id: msg.id,
result: { result: { type: "number", value: 2 } },
}),
);
}
});
}); });
const res = await evaluateJavaScript({ const res = await evaluateJavaScript({
@@ -120,47 +119,35 @@ describe("cdp", () => {
}); });
it("captures an aria snapshot via CDP", async () => { it("captures an aria snapshot via CDP", async () => {
const wsPort = await startWsServer(); const wsPort = await startWsServerWithMessages((msg, socket) => {
if (!wsServer) { if (msg.method === "Accessibility.enable") {
throw new Error("ws server not initialized"); socket.send(JSON.stringify({ id: msg.id, result: {} }));
} return;
}
wsServer.on("connection", (socket) => { if (msg.method === "Accessibility.getFullAXTree") {
socket.on("message", (data) => { socket.send(
const msg = JSON.parse(rawDataToString(data)) as { JSON.stringify({
id?: number; id: msg.id,
method?: string; result: {
}; nodes: [
if (msg.method === "Accessibility.enable") { {
socket.send(JSON.stringify({ id: msg.id, result: {} })); nodeId: "1",
return; role: { value: "RootWebArea" },
} name: { value: "" },
if (msg.method === "Accessibility.getFullAXTree") { childIds: ["2"],
socket.send( },
JSON.stringify({ {
id: msg.id, nodeId: "2",
result: { role: { value: "button" },
nodes: [ name: { value: "OK" },
{ backendDOMNodeId: 42,
nodeId: "1", childIds: [],
role: { value: "RootWebArea" }, },
name: { value: "" }, ],
childIds: ["2"], },
}, }),
{ );
nodeId: "2", }
role: { value: "button" },
name: { value: "OK" },
backendDOMNodeId: 42,
childIds: [],
},
],
},
}),
);
return;
}
});
}); });
const snap = await snapshotAria({ wsUrl: `ws://127.0.0.1:${wsPort}` }); const snap = await snapshotAria({ wsUrl: `ws://127.0.0.1:${wsPort}` });

View File

@@ -27,15 +27,8 @@ describe("pw-tools-core", () => {
downloadUrl: string; downloadUrl: string;
suggestedFilename: string; suggestedFilename: string;
}) { }) {
let downloadHandler: ((download: unknown) => void) | undefined; const harness = createDownloadEventHarness();
const on = vi.fn((event: string, handler: (download: unknown) => void) => {
if (event === "download") {
downloadHandler = handler;
}
});
const off = vi.fn();
const saveAs = vi.fn(async () => {}); const saveAs = vi.fn(async () => {});
setPwToolsCoreCurrentPage({ on, off });
const p = mod.waitForDownloadViaPlaywright({ const p = mod.waitForDownloadViaPlaywright({
cdpUrl: "http://127.0.0.1:18792", cdpUrl: "http://127.0.0.1:18792",
@@ -44,7 +37,7 @@ describe("pw-tools-core", () => {
}); });
await Promise.resolve(); await Promise.resolve();
downloadHandler?.({ harness.trigger({
url: () => params.downloadUrl, url: () => params.downloadUrl,
suggestedFilename: () => params.suggestedFilename, suggestedFilename: () => params.suggestedFilename,
saveAs, saveAs,
@@ -55,7 +48,7 @@ describe("pw-tools-core", () => {
return { res, outPath }; return { res, outPath };
} }
it("waits for the next download and saves it", async () => { function createDownloadEventHarness() {
let downloadHandler: ((download: unknown) => void) | undefined; let downloadHandler: ((download: unknown) => void) | undefined;
const on = vi.fn((event: string, handler: (download: unknown) => void) => { const on = vi.fn((event: string, handler: (download: unknown) => void) => {
if (event === "download") { if (event === "download") {
@@ -63,6 +56,19 @@ describe("pw-tools-core", () => {
} }
}); });
const off = vi.fn(); const off = vi.fn();
setPwToolsCoreCurrentPage({ on, off });
return {
trigger: (download: unknown) => {
downloadHandler?.(download);
},
expectArmed: () => {
expect(downloadHandler).toBeDefined();
},
};
}
it("waits for the next download and saves it", async () => {
const harness = createDownloadEventHarness();
const saveAs = vi.fn(async () => {}); const saveAs = vi.fn(async () => {});
const download = { const download = {
@@ -71,8 +77,6 @@ describe("pw-tools-core", () => {
saveAs, saveAs,
}; };
setPwToolsCoreCurrentPage({ on, off });
const targetPath = path.resolve("/tmp/file.bin"); const targetPath = path.resolve("/tmp/file.bin");
const p = mod.waitForDownloadViaPlaywright({ const p = mod.waitForDownloadViaPlaywright({
cdpUrl: "http://127.0.0.1:18792", cdpUrl: "http://127.0.0.1:18792",
@@ -82,21 +86,15 @@ describe("pw-tools-core", () => {
}); });
await Promise.resolve(); await Promise.resolve();
expect(downloadHandler).toBeDefined(); harness.expectArmed();
downloadHandler?.(download); harness.trigger(download);
const res = await p; const res = await p;
expect(saveAs).toHaveBeenCalledWith(targetPath); expect(saveAs).toHaveBeenCalledWith(targetPath);
expect(res.path).toBe(targetPath); expect(res.path).toBe(targetPath);
}); });
it("clicks a ref and saves the resulting download", async () => { it("clicks a ref and saves the resulting download", async () => {
let downloadHandler: ((download: unknown) => void) | undefined; const harness = createDownloadEventHarness();
const on = vi.fn((event: string, handler: (download: unknown) => void) => {
if (event === "download") {
downloadHandler = handler;
}
});
const off = vi.fn();
const click = vi.fn(async () => {}); const click = vi.fn(async () => {});
setPwToolsCoreCurrentRefLocator({ click }); setPwToolsCoreCurrentRefLocator({ click });
@@ -108,8 +106,6 @@ describe("pw-tools-core", () => {
saveAs, saveAs,
}; };
setPwToolsCoreCurrentPage({ on, off });
const targetPath = path.resolve("/tmp/report.pdf"); const targetPath = path.resolve("/tmp/report.pdf");
const p = mod.downloadViaPlaywright({ const p = mod.downloadViaPlaywright({
cdpUrl: "http://127.0.0.1:18792", cdpUrl: "http://127.0.0.1:18792",
@@ -120,10 +116,10 @@ describe("pw-tools-core", () => {
}); });
await Promise.resolve(); await Promise.resolve();
expect(downloadHandler).toBeDefined(); harness.expectArmed();
expect(click).toHaveBeenCalledWith({ timeout: 1000 }); expect(click).toHaveBeenCalledWith({ timeout: 1000 });
downloadHandler?.(download); harness.trigger(download);
const res = await p; const res = await p;
expect(saveAs).toHaveBeenCalledWith(targetPath); expect(saveAs).toHaveBeenCalledWith(targetPath);