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,18 +55,7 @@ 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) {
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?: { url?: string };
};
if (msg.method !== "Target.createTarget") { if (msg.method !== "Target.createTarget") {
return; return;
} }
@@ -54,7 +66,6 @@ describe("cdp", () => {
}), }),
); );
}); });
});
httpServer = createServer((req, res) => { httpServer = createServer((req, res) => {
if (req.url === "/json/version") { if (req.url === "/json/version") {
@@ -82,18 +93,7 @@ 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) {
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?: { expression?: string };
};
if (msg.method === "Runtime.enable") { if (msg.method === "Runtime.enable") {
socket.send(JSON.stringify({ id: msg.id, result: {} })); socket.send(JSON.stringify({ id: msg.id, result: {} }));
return; return;
@@ -108,7 +108,6 @@ describe("cdp", () => {
); );
} }
}); });
});
const res = await evaluateJavaScript({ const res = await evaluateJavaScript({
wsUrl: `ws://127.0.0.1:${wsPort}`, wsUrl: `ws://127.0.0.1:${wsPort}`,
@@ -120,17 +119,7 @@ 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) {
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;
};
if (msg.method === "Accessibility.enable") { if (msg.method === "Accessibility.enable") {
socket.send(JSON.stringify({ id: msg.id, result: {} })); socket.send(JSON.stringify({ id: msg.id, result: {} }));
return; return;
@@ -158,10 +147,8 @@ describe("cdp", () => {
}, },
}), }),
); );
return;
} }
}); });
});
const snap = await snapshotAria({ wsUrl: `ws://127.0.0.1:${wsPort}` }); const snap = await snapshotAria({ wsUrl: `ws://127.0.0.1:${wsPort}` });
expect(snap.nodes.length).toBe(2); expect(snap.nodes.length).toBe(2);

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);