/** * @file Tests for PdfView: pdf.js (mocked — jsdom has no canvas) draws one * canvas per page, scripting off, and a PDF that cannot be read says so. * @author Nguyễn Ngọc Trí Vĩ */ import { describe, it, expect, vi, beforeEach, afterEach } from "vitest"; import { render, screen, waitFor } from "@testing-library/react"; import "../../i18n"; const getDocument = vi.fn(); vi.mock("pdfjs-dist/legacy/build/pdf.mjs", () => ({ GlobalWorkerOptions: { workerSrc: "" }, getDocument: (...a: unknown[]) => getDocument(...a), })); import { PdfView } from "../PdfView"; const realFetch = globalThis.fetch; beforeEach(() => { getDocument.mockReset(); globalThis.fetch = vi.fn( async () => new Response(new Uint8Array([37, 80, 68, 70])) ) as typeof fetch; }); afterEach(() => { globalThis.fetch = realFetch; }); describe("PdfView", () => { it("draws every page on its own canvas, with XFA off", async () => { const render1 = vi.fn(() => ({ promise: Promise.resolve() })); getDocument.mockReturnValue({ destroy: vi.fn(), promise: Promise.resolve({ numPages: 3, getPage: async () => ({ getViewport: ({ scale }: { scale: number }) => ({ width: 600 * scale, height: 800 * scale, }), render: render1, }), }), }); const { container } = render(); await waitFor(() => expect(container.querySelectorAll("canvas")).toHaveLength(3)); expect(render1).toHaveBeenCalledTimes(3); expect(getDocument.mock.calls[0]![0]).toMatchObject({ enableXfa: false }); expect(screen.getByLabelText("Page 2")).toBeInTheDocument(); }); it("says so when the file cannot be read", async () => { getDocument.mockReturnValue({ destroy: vi.fn(), promise: Promise.reject(new Error("bad")) }); render(); expect(await screen.findByText(/could not be shown/)).toBeInTheDocument(); }); });