Skip to content

Chapter 14 of 17

Test the App ​

Test the app's workflows the way a user runs them: open a note, type, use the menus, and check what lands in the notes folder. The tests render the whole app in a headless session, find widgets through the accessibility tree, and work on real files in a temporary folder, without mocks.

The project already has the testing setup you chose when scaffolding it: Vitest, @gtkx/testing, the test script and vitest.config.ts. Testing covers the tools in full.

A temporary notes folder ​

Replace vitest.config.ts:

vitest.config.ts
ts
import gtkx from "@gtkx/cli/vitest-plugin";
import { defineConfig } from "vitest/config";

export default defineConfig({
    plugins: [gtkx()],
    test: {
        include: ["tests/**/*.test.{ts,tsx}"],
        setupFiles: ["./tests/setup.ts"],
        env: {
            LANG: "C.UTF-8",
            LANGUAGE: "en",
            LC_ALL: "C.UTF-8",
        },
    },
});
  • setupFiles runs tests/setup.ts in each test file's worker before the file's tests.
  • env runs the tests in the C locale with English messages, so the names they look for stay the same whatever the language of the machine.

Create tests/setup.ts:

tests/setup.ts
ts
import * as Gio from "@gtkx/gi/gio";
import { cpSync, mkdtempSync, rmSync, utimesSync } from "node:fs";
import { tmpdir } from "node:os";
import { join } from "node:path";
import { afterAll, beforeEach } from "vitest";
import schema from "../data/dev.gtkx.Notes.gschema.xml";

const root = mkdtempSync(join(tmpdir(), "gtkx-notes-"));
const folder = join(root, "Notes");

process.env.XDG_DATA_HOME = join(root, "data");

beforeEach(() => {
    rmSync(folder, { recursive: true, force: true });
    cpSync(join(import.meta.dirname, "fixtures"), folder, { recursive: true });
    utimesSync(
        join(folder, "Groceries.md"),
        new Date("2026-11-01"),
        new Date("2026-11-01"),
    );
    utimesSync(
        join(folder, "Reading list.md"),
        new Date("2026-11-02"),
        new Date("2026-11-02"),
    );

    const settings = Gio.Settings.new(schema.id);
    for (const key of Object.keys(schema.keys)) {
        settings.reset(key);
    }
    settings.setString("folder", folder);
});

afterAll(() => {
    rmSync(root, { recursive: true, force: true });
});
  • XDG_DATA_HOME points into a temporary directory, so a note moved to the trash goes to a trash there instead of yours. GLib reads the variable once, when the test file imports GTKX, so the setup file sets it at the top level rather than in beforeEach. See Test data and settings.
  • Before each test, beforeEach copies the fixtures into a new notes folder and gives them fixed modification times, so the list's newest-first order is known.
  • Tests use GLib's in-memory settings backend and never touch your settings. A value one test writes would stay for the next test in the file, so beforeEach resets every key in the schema and then points folder at the new notes folder.

The fixtures are two notes. Create tests/fixtures/Groceries.md:

tests/fixtures/Groceries.md
md
# Groceries

- Oat milk
- Coffee beans
- Lemons

And tests/fixtures/Reading list.md:

tests/fixtures/Reading list.md
md
# Reading list

*The Left Hand of Darkness* by Ursula K. Le Guin.

Find widgets by role and name ​

Create tests/notes.test.tsx with the suite below.

The complete tests/notes.test.tsx
tests/notes.test.tsx
tsx
import * as Gio from "@gtkx/gi/gio";
import * as Gtk from "@gtkx/gi/gtk";
import { rootElement } from "@gtkx/react";
import * as Adw from "@gtkx/gi/adw";
import { act, render, screen, userEvent, waitFor, within } from "@gtkx/testing";
import {
    chmodSync,
    existsSync,
    mkdirSync,
    readdirSync,
    readFileSync,
    rmSync,
    writeFileSync,
} from "node:fs";
import { dirname, join } from "node:path";
import { describe, expect, it, onTestFinished } from "vitest";
import schema from "../data/dev.gtkx.Notes.gschema.xml";
import { App } from "../src/app.js";

const notesFolder = (): string =>
    Gio.Settings.new(schema.id).getString("folder");

const noteRows = (): Promise<Gtk.Widget[]> =>
    screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM);

const openNote = async (name: string): Promise<Gtk.TextView> => {
    await userEvent.click(
        await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, { name }),
    );

    return screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, {
        name: "Note text",
        as: Gtk.TextView,
    });
};

const IDEAS =
    "---\ntags: [work, ideas]\n---\n# Ideas\n\nA notes app over **plain files**\n";

const findPreview = async () =>
    within(
        await screen.findByRole(Gtk.AccessibleRole.DOCUMENT, {
            name: "Preview",
        }),
    );

const editorText = (view: Gtk.TextView): string => {
    const buffer = view.getBuffer();

    return buffer.getText(buffer.getStartIter(), buffer.getEndIter(), false);
};

describe("Notes", () => {
    it("lists the Markdown files in the folder, newest first", async () => {
        await render(<App />, { container: rootElement });

        const [first, second] = await noteRows();
        expect(first).toHaveAccessibleName("Reading list");
        expect(second).toHaveAccessibleName("Groceries");
    });

    it("says when the notes folder can't be opened, until another one is chosen", async () => {
        const folder = notesFolder();
        const file = join(dirname(folder), "Not a folder");
        writeFileSync(file, "");
        Gio.Settings.new(schema.id).setString("folder", file);
        await render(<App />, { container: rootElement });

        expect(await screen.findByText("Can’t Open Folder")).toBeDefined();

        await act(() => {
            Gio.Settings.new(schema.id).setString("folder", folder);
        });

        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeDefined();
        expect(screen.queryByText("Can’t Open Folder")).toBeNull();
    });

    it("opens a note in the editor", async () => {
        await render(<App />, { container: rootElement });

        const editor = await openNote("Groceries");

        expect(editorText(editor)).toBe(
            readFileSync(join(notesFolder(), "Groceries.md"), "utf8"),
        );
    });

    it("saves what is typed to the note's file", async () => {
        await render(<App />, { container: rootElement });

        const editor = await openNote("Groceries");
        await userEvent.type(editor, "- Rice\n");

        await waitFor(() => {
            expect(
                readFileSync(join(notesFolder(), "Groceries.md"), "utf8"),
            ).toContain("- Rice");
        });
    });

    it("shows notes added and removed outside the app", async () => {
        await render(<App />, { container: rootElement });
        await noteRows();

        writeFileSync(
            join(notesFolder(), "Ideas.md"),
            "A notes app over plain files\n",
        );
        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Ideas",
            }),
        ).toBeDefined();

        rmSync(join(notesFolder(), "Groceries.md"));
        await waitFor(() => {
            expect(
                screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, {
                    name: "Groceries",
                }),
            ).toBeNull();
        });
    });

    it("reloads an open note changed outside the app", async () => {
        await render(<App />, { container: rootElement });

        const editor = await openNote("Groceries");
        writeFileSync(
            join(notesFolder(), "Groceries.md"),
            "# Groceries\n\n- Bread\n",
        );

        await waitFor(() => {
            expect(editorText(editor)).toBe("# Groceries\n\n- Bread\n");
        });
    });

    it("takes another program's change over edits still waiting to be saved", async () => {
        await render(<App />, { container: rootElement });

        const editor = await openNote("Groceries");
        await userEvent.type(editor, "- Rice\n");
        writeFileSync(
            join(notesFolder(), "Groceries.md"),
            "# Groceries\n\n- Bread\n",
        );

        expect(
            await screen.findByText(
                "Another program replaced your unsaved edits to “Groceries”",
            ),
        ).toBeDefined();
        expect(editorText(editor)).toBe("# Groceries\n\n- Bread\n");
        expect(readFileSync(join(notesFolder(), "Groceries.md"), "utf8")).toBe(
            "# Groceries\n\n- Bread\n",
        );
    });

    it("creates an untitled note and opens it", async () => {
        await render(<App />, { container: rootElement });

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.BUTTON, {
                name: "New Note (Ctrl+N)",
            }),
        );

        const editor = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, {
            name: "Note text",
            as: Gtk.TextView,
        });
        expect(editorText(editor)).toBe("");
        expect(existsSync(join(notesFolder(), "Untitled.md"))).toBe(true);
        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Untitled",
            }),
        ).toBeDefined();
    });

    it("numbers a new note when the name is taken", async () => {
        writeFileSync(join(notesFolder(), "Untitled.md"), "");
        await render(<App />, { container: rootElement });

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.BUTTON, {
                name: "New Note (Ctrl+N)",
            }),
        );

        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Untitled 2",
            }),
        ).toBeDefined();
        expect(readFileSync(join(notesFolder(), "Untitled.md"), "utf8")).toBe(
            "",
        );
    });

    it("renames the open note's file", async () => {
        await render(<App />, { container: rootElement });
        const text = readFileSync(join(notesFolder(), "Groceries.md"), "utf8");

        await openNote("Groceries");
        await userEvent.click(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Note Menu" }),
        );
        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, {
                name: "Rename…",
            }),
        );
        const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, {
            name: "Note name",
        });
        await userEvent.clear(entry);
        await userEvent.type(entry, "Shopping{Enter}");

        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Shopping",
            }),
        ).toBeDefined();
        expect(readFileSync(join(notesFolder(), "Shopping.md"), "utf8")).toBe(
            text,
        );
        expect(existsSync(join(notesFolder(), "Groceries.md"))).toBe(false);
    });

    it("won't rename a note to a name already taken", async () => {
        await render(<App />, { container: rootElement });

        await openNote("Groceries");
        await userEvent.click(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Note Menu" }),
        );
        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, {
                name: "Rename…",
            }),
        );
        const entry = await screen.findByRole(Gtk.AccessibleRole.TEXT_BOX, {
            name: "Note name",
        });
        await userEvent.clear(entry);
        await userEvent.type(entry, "Reading list");

        expect(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Rename" }),
        ).toBeDisabled();
    });

    it("moves a note to the trash and undoes it", async () => {
        await render(<App />, { container: rootElement });
        const path = join(notesFolder(), "Groceries.md");
        const text = readFileSync(path, "utf8");

        await openNote("Groceries");
        await userEvent.click(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Note Menu" }),
        );
        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, {
                name: "Move to Trash",
            }),
        );

        expect(
            await screen.findByText("“Groceries” moved to Trash"),
        ).toBeDefined();
        expect(existsSync(path)).toBe(false);
        expect(
            readdirSync(
                join(process.env.XDG_DATA_HOME ?? "", "Trash", "files"),
            ),
        ).toContain("Groceries.md");
        expect(
            screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeNull();

        await userEvent.click(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Undo" }),
        );

        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeDefined();
        expect(readFileSync(path, "utf8")).toBe(text);
    });

    it("follows the style chosen in Preferences", async () => {
        await render(<App />, { container: rootElement });

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.BUTTON, {
                name: "Main Menu",
            }),
        );
        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, {
                name: "Preferences",
            }),
        );
        await userEvent.selectOptions(
            await screen.findByRole(Gtk.AccessibleRole.COMBO_BOX, {
                name: "Style",
            }),
            2,
        );

        await waitFor(() => {
            expect(Adw.StyleManager.getDefault().getColorScheme()).toBe(
                Adw.ColorScheme.FORCE_DARK,
            );
        });
    });

    it("switches to another folder with the window and Preferences open", async () => {
        const otherFolder = join(dirname(notesFolder()), "Other notes");
        mkdirSync(otherFolder, { recursive: true });
        writeFileSync(join(otherFolder, "Ideas.md"), IDEAS);
        await render(<App />, { container: rootElement });
        const root = (await openNote("Groceries")).getRoot();

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.BUTTON, {
                name: "Main Menu",
            }),
        );
        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, {
                name: "Preferences",
            }),
        );
        await act(() => {
            Gio.Settings.new(schema.id).setString("folder", otherFolder);
        });

        const ideas = await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
            name: "Ideas",
        });
        expect(ideas.getRoot()).toBe(root);
        expect(
            screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeNull();
        expect(
            screen.queryByRole(Gtk.AccessibleRole.TEXT_BOX, {
                name: "Note text",
            }),
        ).toBeNull();
        expect(
            await screen.findByRole(Gtk.AccessibleRole.COMBO_BOX, {
                name: "Style",
            }),
        ).toBeDefined();

        await userEvent.keyboard(
            screen.getByRole(Gtk.AccessibleRole.DIALOG, {
                name: "Preferences",
            }),
            "{Escape}",
        );
        await userEvent.keyboard(ideas, "{F2}");
        await expect(
            screen.findByRole(Gtk.AccessibleRole.ALERT_DIALOG, {
                name: "Rename Note",
            }),
        ).rejects.toThrow();
    });

    it("restores a trashed note into its own folder after a switch", async () => {
        const folder = notesFolder();
        const otherFolder = join(dirname(folder), "Other notes");
        mkdirSync(otherFolder, { recursive: true });
        writeFileSync(join(otherFolder, "Ideas.md"), IDEAS);
        const text = readFileSync(join(folder, "Groceries.md"), "utf8");
        await render(<App />, { container: rootElement });

        await openNote("Groceries");
        await userEvent.click(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Note Menu" }),
        );
        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.MENU_ITEM, {
                name: "Move to Trash",
            }),
        );
        await screen.findByText("“Groceries” moved to Trash");
        await act(() => {
            Gio.Settings.new(schema.id).setString("folder", otherFolder);
        });
        await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
            name: "Ideas",
        });
        await userEvent.click(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, { name: "Undo" }),
        );

        await waitFor(() => {
            expect(readFileSync(join(folder, "Groceries.md"), "utf8")).toBe(
                text,
            );
        });
        expect(existsSync(join(otherFolder, "Groceries.md"))).toBe(false);
        expect(
            screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeNull();

        await act(() => {
            Gio.Settings.new(schema.id).setString("folder", folder);
        });
        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeDefined();
    });

    it("shows the open note as rendered Markdown", async () => {
        await render(<App />, { container: rootElement });

        await openNote("Groceries");
        await userEvent.click(
            screen.getByRole(Gtk.AccessibleRole.TOGGLE_BUTTON, {
                name: "Preview (Ctrl+Shift+P)",
            }),
        );

        const preview = await findPreview();
        expect(
            preview.getByRole(Gtk.AccessibleRole.HEADING, {
                name: "Groceries",
            }),
        ).toBeVisible();
        expect(preview.getByText("Oat milk")).toBeVisible();
        expect(
            screen.queryByRole(Gtk.AccessibleRole.TEXT_BOX, {
                name: "Note text",
            }),
        ).toBeNull();
    });

    it("opens the note a preview link points to", async () => {
        writeFileSync(
            join(notesFolder(), "Index.md"),
            "[Shopping list](Groceries.md)\n",
        );
        Gio.Settings.new(schema.id).setBoolean("preview", true);
        await render(<App />, { container: rootElement });

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Index",
            }),
        );
        await userEvent.keyboard(
            (await findPreview()).getByText("Shopping list"),
            "{Enter}",
        );

        expect(
            await screen.findByRole(Gtk.AccessibleRole.HEADING, {
                name: "Groceries",
            }),
        ).toBeVisible();
    });

    it("completes a link to another note after [[", async () => {
        await render(<App />, { container: rootElement });

        const editor = await openNote("Groceries");
        await userEvent.type(editor, "[[read");
        await within(editor).findByText("Reading list");
        await userEvent.keyboard(editor, "{Enter}");

        expect(editorText(editor)).toMatch(
            /\[Reading list\]\(<Reading list\.md>\)$/,
        );
        await waitFor(() => {
            expect(
                readFileSync(join(notesFolder(), "Groceries.md"), "utf8"),
            ).toContain("[Reading list](<Reading list.md>)");
        });
    });

    it("completes a link from letters spread through a note's name", async () => {
        await render(<App />, { container: rootElement });

        const editor = await openNote("Groceries");
        await userEvent.type(editor, "[[rdlst");

        expect(await within(editor).findByText("Reading list")).toBeDefined();
    });

    it("shows each note's first paragraph as plain text", async () => {
        await render(<App />, { container: rootElement });

        expect(
            await screen.findByText(
                "The Left Hand of Darkness by Ursula K. Le Guin.",
            ),
        ).toBeVisible();
        expect(screen.getByText("Oat milk")).toBeVisible();
    });

    it("says when a note's tags can't be read and still shows the note", async () => {
        writeFileSync(
            join(notesFolder(), "Ideas.md"),
            "---\ntags: [ideas, 2026]\n---\n# Ideas\n\nPlain files.\n",
        );
        Gio.Settings.new(schema.id).setBoolean("preview", true);
        await render(<App />, { container: rootElement });

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Ideas",
            }),
        );

        const preview = await findPreview();
        expect(
            await preview.findByText(/^Couldn’t read the tags/),
        ).toBeVisible();
        expect(preview.getByText("Plain files.")).toBeVisible();
        expect(preview.queryByText("#ideas")).toBeNull();
    });

    it("filters the notes by a tag from their front matter", async () => {
        writeFileSync(join(notesFolder(), "Ideas.md"), IDEAS);
        await render(<App />, { container: rootElement });

        await userEvent.selectOptions(
            await screen.findByRole(Gtk.AccessibleRole.COMBO_BOX, {
                name: "All Notes",
            }),
            2,
        );

        await waitFor(() => {
            expect(
                screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, {
                    name: "Groceries",
                }),
            ).toBeNull();
        });
        expect(
            screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, { name: "Ideas" }),
        ).toBeDefined();
        expect(screen.getByText("A notes app over plain files")).toBeVisible();
    });

    it("previews a note's tags without its front matter", async () => {
        writeFileSync(join(notesFolder(), "Ideas.md"), IDEAS);
        Gio.Settings.new(schema.id).setBoolean("preview", true);
        await render(<App />, { container: rootElement });

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Ideas",
            }),
        );

        const preview = await findPreview();
        expect(
            preview.getByRole(Gtk.AccessibleRole.HEADING, { name: "Ideas" }),
        ).toBeVisible();
        expect(preview.getByText("#work")).toBeVisible();
        expect(preview.queryByText("tags: [work, ideas]")).toBeNull();
    });

    it("finds notes by their text", async () => {
        await render(<App />, { container: rootElement });

        await userEvent.type(
            await screen.findByRole(Gtk.AccessibleRole.SEARCH_BOX, {
                name: "Search Notes",
            }),
            "lemons",
        );

        await waitFor(() => {
            expect(
                screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, {
                    name: "Reading list",
                }),
            ).toBeNull();
        });
        expect(
            screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeDefined();
    });

    it("keeps search results in step with the notes", async () => {
        await render(<App />, { container: rootElement });
        const listed = (name: string) =>
            screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, { name });

        await userEvent.type(
            await screen.findByRole(Gtk.AccessibleRole.SEARCH_BOX, {
                name: "Search Notes",
            }),
            "lemons",
        );
        await waitFor(() => expect(listed("Reading list")).toBeNull());

        writeFileSync(
            join(notesFolder(), "Reading list.md"),
            "# Reading list\n\nWhen life gives you lemons.\n",
        );
        writeFileSync(
            join(notesFolder(), "Pesto.md"),
            "# Pesto\n\nBasil, pine nuts, lemons.\n",
        );
        writeFileSync(
            join(notesFolder(), "Groceries.md"),
            "# Groceries\n\n- Bread\n",
        );
        await waitFor(() => {
            expect(listed("Groceries")).toBeNull();
            expect(listed("Reading list")).not.toBeNull();
            expect(listed("Pesto")).not.toBeNull();
        });
        expect(screen.queryByText("Couldn’t search the notes")).toBeNull();
    });

    it("focuses the search entry on Ctrl+F", async () => {
        await render(<App />, { container: rootElement });

        const editor = await openNote("Groceries");
        await userEvent.keyboard(editor, "{Control>}f{/Control}");

        expect(
            screen.getByRole(Gtk.AccessibleRole.SEARCH_BOX, {
                name: "Search Notes",
            }),
        ).toHaveFocus();
    });

    it("says when a note can't be saved", async () => {
        await render(<App />, { container: rootElement });
        const path = join(notesFolder(), "Groceries.md");
        chmodSync(notesFolder(), 0o555);
        onTestFinished(() => chmodSync(notesFolder(), 0o755));

        const editor = await openNote("Groceries");
        await userEvent.type(editor, "- Rice\n");

        expect(
            await screen.findByText("Couldn’t save “Groceries”"),
        ).toBeDefined();
        expect(readFileSync(path, "utf8")).not.toContain("- Rice");
    });

    it("says the folder can't be read when it loses read permission while open", async () => {
        await render(<App />, { container: rootElement });
        await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
            name: "Groceries",
        });

        chmodSync(notesFolder(), 0o000);
        onTestFinished(() => chmodSync(notesFolder(), 0o755));

        expect(await screen.findByText("Can’t Open Folder")).toBeDefined();
        expect(screen.getByText(/EACCES/)).toBeDefined();
        expect(
            screen.getByRole(Gtk.AccessibleRole.BUTTON, {
                name: "Preferences",
            }),
        ).toBeDefined();
    });

    it("leaves out a note it can't read until the note can be read again", async () => {
        await render(<App />, { container: rootElement });
        await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
            name: "Groceries",
        });
        const path = join(notesFolder(), "Groceries.md");

        chmodSync(path, 0o000);

        expect(
            await screen.findByText("Couldn’t read “Groceries”"),
        ).toBeDefined();
        await waitFor(() => {
            expect(
                screen.queryByRole(Gtk.AccessibleRole.LIST_ITEM, {
                    name: "Groceries",
                }),
            ).toBeNull();
        });
        expect(
            screen.getByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Reading list",
            }),
        ).toBeDefined();

        chmodSync(path, 0o644);

        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Groceries",
            }),
        ).toBeDefined();
    });

    it("offers to create the first note in an empty folder", async () => {
        rmSync(notesFolder(), { recursive: true });
        await render(<App />, { container: rootElement });

        await userEvent.click(
            await screen.findByRole(Gtk.AccessibleRole.BUTTON, {
                name: "New Note",
            }),
        );

        expect(
            await screen.findByRole(Gtk.AccessibleRole.LIST_ITEM, {
                name: "Untitled",
            }),
        ).toBeDefined();
        expect(existsSync(join(notesFolder(), "Untitled.md"))).toBe(true);
    });
});

The first test checks the order of the list:

tsx
const noteRows = (): Promise<Gtk.Widget[]> =>
    screen.findAllByRole(Gtk.AccessibleRole.LIST_ITEM);

describe("Notes", () => {
    it("lists the Markdown files in the folder, newest first", async () => {
        await render(<App />, { container: rootElement });

        const [first, second] = await noteRows();
        expect(first).toHaveAccessibleName("Reading list");
        expect(second).toHaveAccessibleName("Groceries");
    });
  • render with container: rootElement renders App as src/index.tsx does, with its application element and window, instead of inside a test window. See Rendering a component.
  • screen searches every open window, including dialogs and popovers. Queries take a Gtk.AccessibleRole and an accessible name: the names that earlier chapters gave the rows (the note's name), the editor (Note text) and the search entry (Search Notes). An icon button has no label, so its tooltip names it, as in { name: "Note Menu" }. See Finding widgets.
  • toHaveAccessibleName, toBeVisible and the other widget matchers are available once the file imports @gtkx/testing. See Assertions and debugging.

The as option in openNote keeps only a Gtk.TextView and types the result as one, so editorText can read its buffer.

Check the notes folder ​

The tests read the notes folder to check what the app wrote, and write to it to act as another program would:

tsx
it("saves what is typed to the note's file", async () => {
    await render(<App />, { container: rootElement });

    const editor = await openNote("Groceries");
    await userEvent.type(editor, "- Rice\n");

    await waitFor(() => {
        expect(
            readFileSync(join(notesFolder(), "Groceries.md"), "utf8"),
        ).toContain("- Rice");
    });
});
  • The app saves 400 milliseconds after the last edit, so waitFor retries the assertion until the file has the new text, for up to a second. See Interacting and waiting.
  • "says when a note can't be saved" makes the folder read-only with chmodSync and waits for the error toast. A read-only file isn't enough, because write-file-atomic replaces the file instead of writing into it. Vitest's onTestFinished makes the folder writable again, so the setup can delete it before the next test.

Change settings ​

A test that needs a setting other than its default writes it with Gio.Settings before rendering, as "opens the note a preview link points to" does to open notes in the preview.

A setting written while the app is open updates React state outside the userEvent helpers, so "switches to another folder with the window and Preferences open" writes the new folder inside act:

tsx
await act(() => {
    Gio.Settings.new(schema.id).setString("folder", otherFolder);
});

act applies the updates before the test continues; without it, React warns that an update was not wrapped in act(...).

Type into the editor ​

"completes a link to another note after [[" tests the completion provider from Complete Note Links. userEvent.type(editor, "[[read") inserts one character per edit, as typing does, so GtkSourceView sees the second [ and opens its popup. The popup belongs to the editor, so within(editor) waits for the proposal there and not for the Reading list row in the sidebar. selectOnShow has selected it, and while the popup shows, the keys that keyboard sends go to its list (see Keyboard), so {Enter} inserts the link as it does for a user.

Test the stories ​

The preview's tests render the stories from Develop the Preview in Storybook instead of repeating their Markdown. Create tests/preview.test.tsx:

tests/preview.test.tsx
tsx
import * as Gtk from "@gtkx/gi/gtk";
import { composeStories } from "@gtkx/storybook";
import { render, screen, userEvent } from "@gtkx/testing";
import { expect, it } from "vitest";
import * as stories from "../src/preview/markdown-preview.stories.js";

const { Headings, Links, Tagged } = composeStories(stories);

it("renders each Markdown heading as a heading", async () => {
    await render(<Headings />);

    for (const level of [1, 2, 3, 4, 5, 6]) {
        expect(
            screen.getByRole(Gtk.AccessibleRole.HEADING, {
                name: `Heading ${level}`,
            }),
        ).toBeVisible();
    }
});

it("hands an activated link to its callback", async () => {
    const links: string[] = [];
    await render(
        <Links
            onActivateLink={(uri) => {
                links.push(uri);
                return true;
            }}
        />,
    );

    await userEvent.keyboard(
        screen.getByText("Reading list links to another note."),
        "{Enter}",
    );

    expect(links).toEqual(["Reading list.md"]);
});

it("shows the front matter's tags above the note instead of the front matter", async () => {
    await render(<Tagged />);

    expect(screen.getByText("#work")).toBeVisible();
    expect(screen.getByText("#ideas")).toBeVisible();
    expect(screen.queryByText(/tags:/)).toBeNull();
});
  • composeStories turns each story into a component with the story's arguments applied. See Reuse stories in native tests.
  • A story takes props that override its arguments, so the link test passes its own onActivateLink and collects the targets it receives.
  • These components have no window of their own, so render puts them in a test window.

Run the tests ​

The tests run in a private headless display and session bus, which need Sway and dbus-daemon. Install them as Setup shows, then run:

bash
npm test

To run only the tests whose names contain "trash":

bash
npx vitest run -t trash

Run it ​

npm test passes both files:

txt
 ✓ tests/preview.test.tsx (3 tests)
 ✓ tests/notes.test.tsx (30 tests)

 Test Files  2 passed (2)
      Tests  33 passed (33)

Change openNote("Groceries") in "opens a note in the editor" to openNote("Shopping") and run the tests again. The query fails after a second and lists each accessible role on screen with the names of its widgets, such as the list items Reading list and Groceries. Change it back afterwards.