Skip to content

The platform for continuously improving AI agents.

2.4 KB
Raw Blame
// @vitest-environment jsdom
// covers: console-logic
import { cleanup, render } from "@testing-library/react";
import { afterEach, expect, it, vi } from "vitest";

import type { DatasetUpload } from "@/hooks/use-uploads";
import { Attachment } from "./attachment";

const pdf = vi.hoisted(() => ({ destroy: vi.fn(), started: vi.fn() }));

vi.mock("pdfjs-dist", () => ({
  GlobalWorkerOptions: {},
  getDocument: () => {
    pdf.started();
    // A document still parsing when the tile goes away.
    return { destroy: pdf.destroy, promise: new Promise(() => {}) };
  },
}));
vi.mock("pdfjs-dist/build/pdf.worker.min.mjs?url", () => ({ default: "worker.js" }));

afterEach(cleanup);

const upload = (name: string, status: DatasetUpload["status"]) =>
  ({
    file: Object.assign(new File(["%PDF"], name), {
      arrayBuffer: () => Promise.resolve(new ArrayBuffer(4)),
    }),
    id: name,
    percent: 40,
    status,
  }) as DatasetUpload;

const tile = (entry: DatasetUpload) =>
  render(
    <ul>
      <Attachment compact disabled={false} entry={entry} onRemove={vi.fn()} onRetry={vi.fn()} />
    </ul>
  );

it("draws the upload state in the tile until the file is ready", () => {
  const spinning = (status: DatasetUpload["status"]) => {
    const { container } = tile(upload("rows.csv", status));
    const found = !!container.querySelector('button [data-slot="spinner"]');
    cleanup();
    return found;
  };
  expect(spinning("uploading")).toBe(true);
  expect(spinning("counting")).toBe(true);
  expect(spinning("ready")).toBe(false);
});

it("stops drawing a PDF preview when the tile goes away", async () => {
  const { unmount } = tile(upload("report.pdf", "ready"));
  await vi.waitFor(() => expect(pdf.started).toHaveBeenCalled());
  expect(pdf.destroy).not.toHaveBeenCalled();
  unmount();
  expect(pdf.destroy).toHaveBeenCalled();
});

it("never starts a PDF preview for a tile that went away while its bytes were read", async () => {
  pdf.started.mockClear();
  let read: (bytes: ArrayBuffer) => void = () => undefined;
  const entry = upload("late.pdf", "ready");
  entry.file.arrayBuffer = vi.fn(() => new Promise<ArrayBuffer>((resolve) => (read = resolve)));
  const { unmount } = tile(entry);
  await vi.waitFor(() => expect(entry.file.arrayBuffer).toHaveBeenCalled());
  unmount();
  read(new ArrayBuffer(4));
  await new Promise((resolve) => setTimeout(resolve));
  expect(pdf.started).not.toHaveBeenCalled();
});