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

FontFamilyPicker.browser.test.tsx

82 lines2.4 KB

1import { act } from "react";
2import { createRoot, type Root } from "react-dom/client";
3import { afterEach, beforeEach, describe, expect, it, vi } from "vite-plus/test";
4import { userEvent } from "vite-plus/test/browser";
5​
6const families = vi.hoisted(() => {
7 const families = [
8 "Arial",
9 "Courier New",
10 "Fira Code",
11 "Georgia",
12 "Helvetica",
13 "JetBrains Mono",
14 "Menlo",
15 "Times New Roman",
16 ];
17 // The picker decides at module load whether the engine can list fonts.
18 Object.assign(window, { queryLocalFonts: async () => families.map((family) => ({ family })) });
19 return families;
20});
21​
22vi.mock("../../appearanceFonts", () => ({
23 isMonospaceFamily: () => true,
24 queryInstalledFontFamilies: async () => ({ status: "granted", families }),
25}));
26​
27import { discoverInstalledFonts, FontFamilyPicker } from "./FontFamilyPicker";
28​
29let root: Root;
30let container: HTMLDivElement;
31​
32beforeEach(async () => {
33 vi.stubGlobal("IS_REACT_ACT_ENVIRONMENT", true);
34 container = document.createElement("div");
35 document.body.append(container);
36 root = createRoot(container);
37 await act(async () => discoverInstalledFonts());
38});
39​
40afterEach(async () => {
41 await act(() => root.unmount());
42 container.remove();
43 vi.restoreAllMocks();
44 vi.unstubAllGlobals();
45});
46​
47function highlightedOptions(): string[] {
48 return [...document.querySelectorAll('[role="option"][data-highlighted]')].map(
49 (option) => option.textContent ?? "",
50 );
52​
53describe("FontFamilyPicker", () => {
54 it("highlights, moves through, and selects matches after filtering", async () => {
55 const onSelect = vi.fn();
56 await act(async () =>
57 root.render(
58 <FontFamilyPicker
59 ariaLabel="Code font"
60 defaultFamily="Menlo"
61 selectedFamily=""
62 initialOpen
63 onSelect={onSelect}
64 />,
65 ),
66 );
67​
68 const input = document.querySelector<HTMLInputElement>('input[placeholder="Search fonts…"]');
69 expect(input).not.toBeNull();
70 const press = (key: string) => act(() => userEvent.keyboard(`{${key}}`));
71​
72 // Both matches were already rendered further down the unfiltered list.
73 await act(() => userEvent.type(input!, "co"));
74 await expect.poll(highlightedOptions).toEqual(["Courier New"]);
75​
76 await press("ArrowDown");
77 expect(highlightedOptions()).toEqual(["Fira Code"]);
78​
79 await press("Enter");
80 expect(onSelect).toHaveBeenCalledWith("Fira Code");
81 });
82});