Skip to content

The IDE you know, rebuilt in Rust. IntelliJ IDEA–style keymap, tool windows and search-everywhere in a fast native app: editor, code insight, debugger, Git, terminal, database and HTTP clients for 60+ languages.

2.3 KB
Raw Blame
import { afterEach, expect, it, vi } from "vitest";
import { detectCandidateFonts } from "./candidateFonts";

afterEach(() => vi.restoreAllMocks());
it("probes the legacy list and classifies measured mono and proportional families", () => {
  const ctx = {
    font: "",
    measureText(text: string) {
      if (this.font.includes('"Menlo"')) return { width: 120 };
      if (this.font.includes('"Georgia"')) return { width: text.startsWith("i") ? 60 : 180 };
      return { width: 100 };
    },
  };
  vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(ctx as unknown as CanvasRenderingContext2D);
  expect(detectCandidateFonts()).toEqual([
    { name: "Menlo", monospaced: true },
    { name: "Georgia", monospaced: false },
  ]);
});
it("returns no inferred families when Canvas is absent", () => {
  const remove = vi.spyOn(HTMLCanvasElement.prototype, "remove");
  vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue(null);
  expect(detectCandidateFonts()).toEqual([]);
  expect(remove).toHaveBeenCalledOnce();
});
it("detects user-installed candidates with a connected probe and removes it afterwards", () => {
  const probes: HTMLCanvasElement[] = [];
  vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(function (this: HTMLCanvasElement) {
    probes.push(this);
    const isConnected = () => this.isConnected;
    return {
      font: "",
      measureText(this: { font: string }) {
        return { width: isConnected() && this.font.includes('"Fira Code"') ? 120 : 100 };
      },
    } as unknown as CanvasRenderingContext2D;
  });
  expect(detectCandidateFonts()).toEqual([{ name: "Fira Code", monospaced: true }]);
  expect(probes[0]?.hidden).toBe(true);
  expect(probes[0]?.isConnected).toBe(false);
});
it("contains failures from Canvas and never claims candidates are installed", () => {
  vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockImplementation(() => {
    throw new Error("disabled");
  });
  expect(detectCandidateFonts()).toEqual([]);
});
it("does not treat invalid measurements as available fonts", () => {
  vi.spyOn(HTMLCanvasElement.prototype, "getContext").mockReturnValue({
    font: "",
    measureText: () => ({ width: Number.NaN }),
  } as unknown as CanvasRenderingContext2D);
  expect(detectCandidateFonts()).toEqual([]);
});