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

PdfDocumentNavigation.test.ts

163 lines5.8 KB

1import type { CDPSession } from "playwright-core";
2import { describe, expect, it, vi } from "vite-plus/test";
3​
4import { installPdfDocumentNavigation } from "./PdfDocumentNavigation.ts";
5​
6const source = "https://environment.test/api/assets/signed-token/files/Study%20guide.PDF";
7​
8function fixture(nativePdfViewer = false) {
9 const completed = Promise.withResolvers<{ method: string; params: Record<string, unknown> }>();
10 let paused: (event: {
11 requestId: string;
12 frameId: string;
13 request: { url: string; method: string };
14 responseStatusCode: number;
15 responseHeaders: Array<{ name: string; value: string }>;
16 }) => void = () => {
17 throw new Error("Navigation handler was not installed");
18 };
19 const send = vi.fn(async (method: string, params: Record<string, unknown> = {}) => {
20 if (method === "Runtime.evaluate") return { result: { value: nativePdfViewer } };
21 if (method === "Page.getFrameTree") return { frameTree: { frame: { id: "main" } } };
22 if (
23 method === "Fetch.fulfillRequest" ||
24 method === "Fetch.continueRequest" ||
25 method === "Fetch.failRequest"
26 ) {
27 completed.resolve({ method, params });
28 }
29 return {};
30 });
31 const cdp = {
32 send,
33 on: (_name: string, listener: typeof paused) => {
34 paused = listener;
35 },
36 } as unknown as CDPSession;
37 return {
38 cdp,
39 send,
40 navigate: (
41 url = source,
42 frameId = "main",
43 method = "GET",
44 status = 200,
45 contentType = "application/pdf",
46 ) => {
47 paused({
48 requestId: "request-1",
49 frameId,
50 request: { url, method },
51 responseStatusCode: status,
52 responseHeaders: [{ name: "Content-Type", value: contentType }],
53 });
54 return completed.promise;
55 },
56 };
58​
59describe("PDF document navigation", () => {
60 it("keeps native PDF rendering when the browser supports it", async () => {
61 const test = fixture(true);
62 await installPdfDocumentNavigation(test.cdp);
63 expect(test.send.mock.calls.map(([method]) => method)).toEqual(["Runtime.evaluate"]);
64 });
65​
66 it("commits the PDF URL for client rendering without redirects or server-side PDF rendering", async () => {
67 const test = fixture();
68 await installPdfDocumentNavigation(test.cdp);
69 const { method, params } = await test.navigate();
70 expect(method).toBe("Fetch.fulfillRequest");
71 expect(params).toMatchObject({ responseCode: 200, requestId: "request-1" });
72 expect(params.responseHeaders).toEqual([
73 { name: "Content-Type", value: "text/html; charset=utf-8" },
74 { name: "Cache-Control", value: "no-store" },
75 { name: "Content-Security-Policy", value: "default-src 'none'; sandbox" },
76 { name: "X-Content-Type-Options", value: "nosniff" },
77 ]);
78 expect(Buffer.from(String(params.body), "base64").toString()).toBe(
79 "<!doctype html><html><head><title>Study guide.PDF</title></head><body><h1>Study guide.PDF</h1><p>This PDF is displayed in the connected client.</p></body></html>",
80 );
81 expect(test.send).toHaveBeenCalledWith("Fetch.enable", {
82 patterns: [
83 { urlPattern: "*/api/assets/*", resourceType: "Document", requestStage: "Response" },
84 ],
85 });
86 });
87​
88 it.each([401, 403, 404, 410, 500])(
89 "fails unavailable PDF assets with HTTP %s",
90 async (status) => {
91 const test = fixture();
92 await installPdfDocumentNavigation(test.cdp);
93 expect(await test.navigate(source, "main", "GET", status)).toEqual({
94 method: "Fetch.failRequest",
95 params: { requestId: "request-1", errorReason: "Failed" },
96 });
97 expect(test.send.mock.calls.some(([method]) => method === "Fetch.fulfillRequest")).toBe(
98 false,
99 );
100 },
101 );
102​
103 it("rejects a non-PDF response instead of committing a successful PDF tab", async () => {
104 const test = fixture();
105 await installPdfDocumentNavigation(test.cdp);
106 expect(await test.navigate(source, "main", "GET", 200, "text/html")).toMatchObject({
107 method: "Fetch.failRequest",
108 });
109 });
110​
111 it("allows redirects to reach their asset response", async () => {
112 const test = fixture();
113 await installPdfDocumentNavigation(test.cdp);
114 expect(await test.navigate(source, "main", "GET", 302)).toMatchObject({
115 method: "Fetch.continueRequest",
116 });
117 });
118​
119 it("accepts a partial PDF response", async () => {
120 const test = fixture();
121 await installPdfDocumentNavigation(test.cdp);
122 expect(
123 await test.navigate(source, "main", "GET", 206, "Application/PDF; charset=binary"),
124 ).toMatchObject({
125 method: "Fetch.fulfillRequest",
126 });
127 });
128​
129 it.each([
130 ["https://environment.test/api/assets/token/index.html", "main", "GET"],
131 ["https://example.com/paper.pdf", "main", "GET"],
132 [source, "subframe", "GET"],
133 [source, "main", "POST"],
134 ])("leaves other browser requests alone: %s, %s, %s", async (url, frameId, method) => {
135 const test = fixture();
136 await installPdfDocumentNavigation(test.cdp);
137 expect(await test.navigate(url, frameId, method)).toEqual({
138 method: "Fetch.continueRequest",
139 params: { requestId: "request-1" },
140 });
141 });
142​
143 it("escapes filenames in the browser document", async () => {
144 const test = fixture();
145 await installPdfDocumentNavigation(test.cdp);
146 const result = await test.navigate(
147 "https://environment.test/api/assets/token/%3Cscript%3E.pdf",
148 );
149 expect(Buffer.from(String(result.params.body), "base64").toString()).toContain(
150 "<title>&lt;script>.pdf</title>",
151 );
152 });
153​
154 it("resumes navigation when committing the document fails", async () => {
155 const test = fixture();
156 await installPdfDocumentNavigation(test.cdp);
157 test.send.mockRejectedValueOnce(new Error("Tab closed"));
158 expect(await test.navigate()).toEqual({
159 method: "Fetch.continueRequest",
160 params: { requestId: "request-1" },
161 });
162 });
163});