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:
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",
},
},
});setupFilesrunstests/setup.tsin each test file's worker before the file's tests.envruns 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:
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_HOMEpoints 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 inbeforeEach. See Test data and settings.- Before each test,
beforeEachcopies 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
beforeEachresets every key in the schema and then pointsfolderat the new notes folder.
The fixtures are two notes. Create tests/fixtures/Groceries.md:
# Groceries
- Oat milk
- Coffee beans
- LemonsAnd tests/fixtures/Reading list.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. It covers each feature from the earlier chapters, one test per workflow; the rest of this chapter explains how its tests work.
The complete tests/notes.test.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 } 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("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("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 window = (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(window);
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();
});
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("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("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("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(path, 0o444);
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("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:
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");
});renderwithcontainer: rootElementrendersAppassrc/index.tsxdoes, with its application element and window, instead of inside a test window. See Rendering a component.screensearches every open window, including dialogs and popovers. Queries take aGtk.AccessibleRoleand 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.findByandfindAllByqueries wait for the widget to appear, here for the notes to load.getByqueries expect the widget to be there already, andqueryByqueries returnnullwhen it isn't, to check that something is gone.toHaveAccessibleName,toBeVisibleand 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:
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");
});
});userEventhelpers act as a user does and wait until React has applied the result. Await each one. See Interacting and waiting.- The app saves 400 milliseconds after the last edit, so
waitForretries the assertion until the file has the new text, for up to a second. - "shows notes added and removed outside the app" and "reloads an open note changed outside the app" write and delete files with
node:fsand wait for the list and the editor to follow, which tests the file watching from Save and Watch Files. - "moves a note to the trash and undoes it" finds the moved file under
Trash/filesin the temporaryXDG_DATA_HOME. - "says when a note can't be saved" makes the file read-only with
chmodSyncand waits for the error toast.
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:
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(...). The test then checks that the window it started with now lists the other folder, and that Preferences stayed open.
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. read narrows the popup to Reading list. 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. The test then finds the link in the editor and in the file.
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:
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 tags above the note", async () => {
await render(<Tagged />);
expect(screen.getByText("#work")).toBeVisible();
expect(screen.getByText("#ideas")).toBeVisible();
});composeStoriesturns 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
onActivateLinkand collects the targets it receives. - These components have no window of their own, so
renderputs 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:
npm testEach test starts from the fixtures and the default settings, so any test also runs on its own. To run only the tests whose names contain "trash":
npx vitest run -t trashRun it
npm test passes both files:
✓ tests/preview.test.tsx (3 tests)
✓ tests/notes.test.tsx (22 tests)
Test Files 2 passed (2)
Tests 25 passed (25)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.