Terminal programs render asynchronously: output arrives in chunks, screens redraw, spinners spin. A test that reads the screen at the wrong moment fails randomly. testingterm avoids this the way good browser testing tools do: every check waits.
Assertions retry
await expect(term).toHaveText("Ready");
await expect(term).toHaveText(/\d+ passed/);
await expect(term).not.toHaveText("Loading");
await expect(term).toHaveTitle("vim");
await expect(term).toHaveCursorAt({ col: 2, row: 0 });
await expect(term).toHaveExited({ code: 0 });
await expect(term).toHaveScreen("exact\nscreen contents");
await expect(term.getByText("Error")).not.toBeVisible();
await expect(term.getByText("item")).toHaveCount(3);Each one retries until it passes or the timeout runs out (5 seconds by default; pass { timeout } to change one). Failures include the screen at the moment they gave up.
Regex flags work as in JavaScript: /^ok$/m matches a whole line, /ok/i ignores case.
expect(value) with anything other than a terminal or locator checks once: toBe, toEqual, toBeTruthy, toContain, toMatch, toBeGreaterThan, toBeLessThan, and .not.
Explicit waits
await term.waitForText("Listening on");
const match = await term.waitForText(/port (\d+)/);
await term.waitForGone("Loading...");
await term.waitForStable(200);
await term.waitForIdle(100);
await term.waitForTitle("done");
const { exitCode, signal } = await term.waitForExit();waitForStable(ms): the screen did not change forms. Use it after animations and spinners, before taking screenshots.waitForIdle(ms): the program printed nothing forms.- Add
{ scrollback: true }to text waits to search lines that scrolled off the top.
Waits run inside the engine and resolve the moment the condition holds. If the program exits while you wait for text that never came, the wait fails right away instead of timing out.
Avoiding flaky tests
- Never sleep. A fixed delay is either too short on a slow machine or wasted time on a fast one. Wait for the text, title or exit you actually expect.
- Wait before acting.
getByText(...).click()already waits; with raw coordinates, wait for something on screen first. - Wait for stability before screenshots of screens with animations:
await term.waitForStable(150). - Make the environment fixed. Set
colsandrows, useisolate: trueso user config doesn't leak in, and pass theenvyour program reads. - Assert on what users see, not on internals: the text, the colors (
term.styles()), the exit code. - Prefer strict locators. If text appears twice, choose with
.nth()instead of hoping the first match is the right one.