Testing an app
duolith test builds your project and runs every *.test.ts file under pages/ and components/ in Chromium, with @duolith/testing (decision 0065).
duolith test # the project in this folder
duolith test examples/data --filter likes
duolith test --headed # watch it run
duolith test --json # spec/schemas/cli/test.schema.json
duolith test --file pages/index.test.ts # one test file
duolith test --watch # again after every change, until stopped
duolith test --update-snapshots # rewrite the visual baselines
Chromium comes from Playwright: pnpm exec playwright install chromium once.
A page
// pages/index.test.ts
import { describe, expect, render, test } from "@duolith/testing";
describe("todos", () => {
test("adding a todo shows it in the list", async () => {
const screen = await render("/");
await screen.byLabel("New todo").type("Feed the cat");
await screen.byRole("button", { name: "Add", exact: true }).press();
await expect(screen.byText("Feed the cat")).toBeShown();
await expect(screen.byText("3 things left · 1 done")).toBeShown();
});
});
- Find with
byRole(role, { name }),byText(text)andbyLabel(label); narrow with.within.byText(...)(inside what was found) and.nth(n)(counting from 0). - Act with
press(),hold()(a long press),type(text)andkey("Enter"); move withscreen.navigate("/post/7")andscreen.back(). - Check with
expect(found):toBeShown,toBeHidden,toHaveText,toHaveCount,toBeChecked,toBeUnchecked,toBeDisabled; andexpect(screen):toHavePath,toHaveTitle. Each waits up to five seconds for the screen to catch up. screen.screenshot(path)saves what is shown. Every render is a phone window, 390 by 844, light;render(path, { viewport, colorScheme: "dark" })changes that.
Loaded state and actions
Tests never reach the network. Give loaded state by the key it loads with and actions by the name the page declares them under:
import { expect, fail, render, test } from "@duolith/testing";
const posts = [{ id: 1, author: "Ada", caption: "First light over the harbour.", likes: 12 }];
test("a refused like is rolled back and says why", async () => {
const screen = await render("/posts", {
loads: { posts },
actions: { like: fail("Likes are closed on this post.", 403) },
});
await screen.byRole("button", { name: "Like" }).press();
await expect(screen.byText("Like rolled back: Likes are closed on this post.")).toBeShown();
await expect(screen.byRole("button", { name: "Like" })).toHaveText("♥ 12");
});
A mock is a value, fail(message, status?) (status 400 when left out), pending() (never answers, so the loading or optimistic state stays), or a function of the input. The function runs in the page, so it cannot use the test's variables; write it as an arrow, a function, or a method in shorthand (posts() { return [...] }). await screen.runs("like") lists the inputs an action was called with.
A component
// components/Card.test.ts
import { expect, renderComponent, test } from "@duolith/testing";
test("a card shows its title, its subtitle and what it is given", async () => {
const screen = await renderComponent("Card", { props: { title: "You", subtitle: "Signed in" }, slot: "Hello" });
await expect(screen.byText("You", { exact: true })).toBeShown();
await expect(screen.byText("Signed in")).toBeShown();
await expect(screen.byText("Hello")).toBeShown();
});
Any component file can be rendered by its name, fancy-label.duo as renderComponent("fancy-label").
Platform effects
A page's effects (camera, share, storage, sign-in and every other export of @duolith/effects) can be mocked in render, so a test needs no device, camera or share sheet (decision 0147). Give a function for a function effect, and an object of methods (and values) for an object effect:
import { effectError, expect, render, test } from "@duolith/testing";
test("where there is no share sheet, the link is copied", async () => {
const screen = await render("/share", { effects: { share: () => "copied" } });
await screen.byRole("button", { name: "Share this lake" }).press();
await expect(screen.byText("Link copied")).toBeShown();
expect(await screen.effectCalls("share")).toEqual([[{ title: "Lake Bled", text: "Look at this lake", url: "https://example.com/lake-bled" }]]);
});
test("a camera that fails shows why", async () => {
const screen = await render("/camera", {
effects: {
permissions: { request: () => "granted", status: () => "granted" },
camera: { capture: effectError("E0230", "The camera stopped before the photo was taken.") },
},
});
await screen.byRole("button", { name: "Front camera" }).press();
await expect(screen.byRole("alert")).toHaveText("E0230: The camera stopped before the photo was taken.");
});
- **Any effect listed in
spec/effects/effects.yamlcan be mocked.** There is nothing to register. - A stand-in platform is not mocked. An export marked
mock: true, such asmockLocationormockStore, is a test platform already: use it as it is, or mock the effect it stands in for (location). Naming it ineffectsmakesrender()throw. - An effect you do not mock runs for real, in Chromium.
- **
screen.effectCalls("camera.capture")** gives every call, mocked or not, as plain data. A signal reads"<signal>"and a function reads"<function>". - **
effectError(code, message)** makes the call fail with anEffectError, as the platform would. - An effect that is a function takes one mock, not members:
share: () => "copied"orshare: effectError(...). Members given for one (share: { share: ... }), or a member the effect does not have (camera: { captur: ... }), makerender()throw and say what the effect has, so a mock is never silently ignored.
The page runs at https://duolith.test, a secure context, so sign-in and secure storage work as they do in a browser. examples/effects/pages/share.test.ts has these tests.
Visual baselines
await expect(screen).toMatchSnapshot("home");
await expect(screen.byRole("list")).toMatchSnapshot("todos", { tolerance: 0.01 });
- The first run writes the baseline to
__snapshots__/<test file>/<name>.png, beside the test. Commit it. In CI (CIset), a missing baseline fails the test instead. WithDUOLITH_SNAPSHOTS=read-onlynothing is written or removed at all: a missing baseline fails, and a changed screen fails without its.actual.pngand.diff.png. The tool server'srun_testsruns a project outside its workspace this way. - Each later run compares with it.
- Up to
toleranceof the pixels may differ. The default is 0.001, one in a thousand. - A pixel differs when a colour channel is off by more than
threshold. The default is 0.1.
- Up to
- A failure says how many pixels differ. It writes
<name>.actual.pngand<name>.diff.pngbeside the baseline. The diff shows the differing pixels in red. - **
duolith test --update-snapshots** rewrites every baseline the tests take.
Watching
duolith test --watch runs the tests, then runs them again whenever a file in the project changes, until you stop it. A change in __snapshots__/ does not count. With --json it prints one JSON document per run, one per line. Editors run one file with --file.
When a test misbehaves
- Await every check.
expect(found).toBeShown()waits, so it returns a promise. A check still waiting when the test returns fails the test: "1 check(s) were still waiting when the test returned". - A rejection nothing handles while a test runs fails that test, with its message.
- A test has 30 seconds (set
DUOLITH_TEST_TIMEOUT_MSto change it), and so does loading a test file. Once a test times out it can no longer render, so it cannot disturb the tests after it. - Open timers and sockets are fine: the run ends once the report is written.
- The whole run has 20 minutes (
DUOLITH_TEST_DEADLINE_SECONDS). Past that, a test stuck in a loop is stopped with the browser, andduolith testfails. - **
--filtermust match**: a filter that matches no test's name fails the run, so a typo never passes.
The examples control-flow, data, components and effects have tests to copy from, and so does every duolith create template except blank, tabs and data.