Roc Solid
Markup in Roc · pages on a native server · components in WebAssembly

The ecosystem · packages/testing

Tests that read a page as a person does

Helpers for testing a Roc Solid app. A test finds a heading, a link by its name and a field by its label, as a person using the page does, not by the page's classes.

The same queries, with the same rules, work in a Roc expect and from Node's test runner against the running app, its database and a real browser (four ways to test).

A first test#

The package is plain Roc on no platform, so any module can use it. Name it in the app's header:

app [program] { testing: "../packages/testing/main.roc", pf: platform "…" }

A pure component (view, no !) makes its markup from its props alone, so an expect can render it with Html.to_str, read the HTML with Dom.parse, and ask what a person would see. A small inbox, and how it renders:

site/Demos/TestingInbox.rocx
import pf.Html
import pf.Server
import testing.Dom

## Someone's inbox, as a card: whose it is, how many messages are unread,
## a link to each, and a form to write one. A pure component (`view`, no
## `!`): its markup comes from its props alone, so a test renders it with
## `Html.to_str` and finds things in it as a person would (`testing.Dom`).
TestingInbox := [].{
	view : { name : Str, unread : List(Str) } -> Html
	view = |{ name, unread }|
		<section class="inbox" aria-labelledby="inbox-title">
			<h3 id="inbox-title">{name}'s inbox</h3>
			<p data-testid="unread">{unread.len().to_str()} unread</p>
			<ul aria-label="Unread">
				{...unread.map(|subject| <li><a href={"/mail/${Server.encode_segment(subject)}"}>{subject}</a></li>)}
			</ul>
			<form method="post" action="/mail">
				<label for="inbox-to">To</label>
				<input id="inbox-to" name="to" type="email" />
				<button>Write</button>
			</form>
		</section>
}
…

As it renders (a picture: it does nothing here)

Ada's inbox

2 unread

Its tests sit in the same file, under the component:

site/Demos/TestingInbox.rocx
## Ada's inbox, as a test reads it: rendered to HTML, then parsed.
inbox : List(Str) -> Dom
inbox = |unread| Dom.parse(Html.to_str(TestingInbox.view({ name: "Ada", unread })))
expect inbox([]).text_of(Role("heading")) == Ok("Ada's inbox")
expect inbox(["Lunch?", "Re: the plan"]).texts(Role("link")) == ["Lunch?", "Re: the plan"]
expect inbox(["Lunch?"]).get(Named("link", "Lunch?")).map_ok(|link| link.attr("href")) == Ok(Ok("/mail/Lunch%3F"))
expect inbox(["Lunch?", "Re: the plan"]).text_of(TestId("unread")) == Ok("2 unread")
expect inbox([]).get(Label("To")).map_ok(|field| field.attr("type")) == Ok(Ok("email"))
expect inbox([]).contains(Named("button", "Write"))
expect !inbox([]).contains(Named("button", "Send"))

After rocx generate, roc test main.roc runs them with every other expect in the app. Through rocx check -- roc test main.roc, a failing expect is reported at its line in the .rocx file (errors at your lines). This site's tests run the ones above.

A query that finds exactly one element answers Ok with it. Finding none or several, it answers an error that says what the page has instead, so a failing test tells you what went wrong. What page.get answered for a few queries of the inbox, as this page rendered:

AskedAnswered
page.get(Role("heading"))Ok the <h3>: "Ada's inbox"
page.get(Named("link", "Lunch?"))Ok the <a>: "Lunch?"
page.get(Label("To"))Ok the <input>
page.get(TestId("unread"))Ok the <p>: "2 unread"
page.get(Role("link"))TooMany 2 elements are a link
page.get(Named("button", "Send"))NotFound nothing is a button named "Send"; the buttons here: "Write"
How the table is made: site/Demos/TestingAnswers.rocx
site/Demos/TestingAnswers.rocx
import pf.Html
import testing.Dom
import TestingInbox

## What `page.get` answers for a few queries of Ada's inbox (two unread): the testing package's docs
## page shows it, asked as the page renders, so what it shows is what the package says.
TestingAnswers := [].{
	view : {} -> Html
	view = |{}|
		<table>
			<thead><tr><th>Asked</th><th>Answered</th></tr></thead>
			<tbody>
				{...answers.map(|row| <tr><td><code>{row.asked}</code></td><td><code>{row.kind}</code> {row.said}</td></tr>)}
			</tbody>
		</table>

	<style>
		/* Each query whole, on one line, and the answer readable: a narrow screen scrolls the table sideways. */
		td:first-child code {
			white-space: nowrap;
		}

		td:last-child {
			min-width: 12rem;
		}
	</style>
}

## Each query, as it is written, and what `get` answered: `Ok` and the element, or why not.
answers : List({ asked : Str, kind : Str, said : Str })
answers = {
	page = Dom.parse(Html.to_str(TestingInbox.view({ name: "Ada", unread: ["Lunch?", "Re: the plan"] })))
	[Role("heading"), Named("link", "Lunch?"), Label("To"), TestId("unread"), Role("link"), Named("button", "Send")].map(
		|query| {
			asked = "page.get(${written(query)})"
			match page.get(query) {
				Ok(found) => { asked, kind: "Ok", said: if (found.text().is_empty()) "the <${found.tag()}>" else "the <${found.tag()}>: \"${found.text()}\"" }
				Err(NotFound(why)) => { asked, kind: "NotFound", said: why }
				Err(TooMany(why)) => { asked, kind: "TooMany", said: why }
			}
		},
	)
}

## A query as Roc writes it.
written : Dom.Query -> Str
written = |query|
	match query {
		Role(role) => "Role(${quoted(role)})"
		Named(role, name) => "Named(${quoted(role)}, ${quoted(name)})"
		Text(text) => "Text(${quoted(text)})"
		Label(text) => "Label(${quoted(text)})"
		TestId(id) => "TestId(${quoted(id)})"
		Tag(tag) => "Tag(${quoted(tag)})"
		Attr(name, value) => "Attr(${quoted(name)}, ${quoted(value)})"
	}

quoted : Str -> Str
quoted = |text| "\"${text}\""

expect answers.map(|row| row.kind) == ["Ok", "Ok", "Ok", "Ok", "TooMany", "NotFound"]
expect answers.get(5).map_ok(|row| row.said) == Ok("nothing is a button named \"Send\"; the buttons here: \"Write\"")

Four ways to test#

Rules and pure components, in Roc

An expect beside the code. Html.to_str renders a pure component, and Dom.parse reads it. Fast, typed, and run by roc test.

The app, over HTTP, from Node

A node:test file builds the app as a deploy does, starts its server on its own port, and asks what a browser would: pages, forms, endpoints, events, and the mail it sent.

Its database and its jobs

Each test gets its own database, Postgres or SQLite, migrated by the server. A test can wait for the jobs it caused and see how each ended.

A real browser

Chromium's headless shell, or Zen or Firefox. The page hydrates strictly, and the test clicks and types as a person does. A component with signals is tested through its story.

The queries#

Roc and JavaScript share the queries and their rules. The JavaScript ones use Testing Library's names.

In RocIn JavaScriptFinds
Role(role) getByRole(role) elements with that ARIA role, either written (role="tab") or implied by the tag: a <button> is a button, an <a href> a link, an <h2> a heading, a <ul> a list, an <input type="checkbox"> a checkbox
Named(role, name) getByRole(role, { name }) elements with that role whose accessible name is name. The name comes from aria-labelledby, aria-label, a <label>, alt, the element's text (for a button, a link, a heading or a cell), or title
Text(text)getByText(text)elements whose own text is text, not counting their children's
Label(text) getByLabelText(text) the field that a <label> with that text names (by for, or by wrapping it), or whose aria-label or aria-labelledby says it
TestId(id)getByTestId(id)the element whose data-testid is id
Tag(tag), Attr(name, value)(none)elements by tag, or by an attribute's value, hidden or not

Text is compared as a reader sees it: whitespace collapsed and trimmed. Roles, names, text and labels skip what a reader can't see: an element marked hidden or aria-hidden="true", or styled display: none or visibility: hidden, with everything inside it; and <head>, <script>, <style>, <template> and <noscript>. In JavaScript, a name or text may also be a RegExp, and getByRole also takes a heading's level and { hidden: true }.

Dom, in Roc#

Dom.parse(html) reads HTML into a tree. It expects closed elements, as Roc Solid writes them and a browser serializes them. A query on an element looks only inside it, and two Doms compare with ==.

FunctionGives
page.get(query)Try(Dom, [NotFound(Str), TooMany(Str)]): the one element, or why not
page.first(query), page.all(query)the first match; every match, in the page's order
page.contains(query), page.count(query)whether anything matches; how many do
page.text_of(query), page.texts(query)the text of the one match; the text of each
node.text()what a reader reads in it, whitespace collapsed
node.attr(name), node.tag(), node.has_class(class)an attribute (Err(Missing) when there is none); its tag; whether it has that class
page.roles()every role and name a reader can reach: print it with dbg when a query finds nothing

From Node#

For what a pure component can't show (pages, forms, endpoints, the database), test the running app from node:test. buildForTests builds the app as a deploy does (rocx generate, the browser's wasm, the server); a markup problem, type error or warning throws, reported at its line in the .rocx file. The server is a quick dev build unless ROCX_TEST_OPT=speed asks for a release's. The files of one node --test run share one build: the first builds while the others wait. startServer starts that server on a free port, usually once for a file's tests:

packages/testing/test/app.test.mjs
before(async () => {
	if (skip) return;
	dir = writeFixture(mkdtempSync(join(tmpdir(), "rocx-testing-")));
	const built = await buildForTests(dir, { dev: true });
	if (!skipDb) db = await testDatabase();
	app = await startServer(built.server, { statics: built.statics, database: db?.url, env: { MAIL_FROM: "Notes <notes@example.com>" } });
	for (const engine of ["chromium", "gecko"]) browsers[engine] = await launchBrowser({ engine });
});

after(async () => {
	for (const browser of Object.values(browsers)) await browser?.close();
	await app?.stop();
	await db?.drop();
	if (dir) rmSync(dir, { recursive: true, force: true });
});

app.client() is one person at a browser, with their own cookie jar. Every answer has its status, its text, and a dom with the queries:

packages/testing/test/app.test.mjs
test("a page, found in by role, name, label and test id; the error page", { skip }, async () => {
	const person = app.client();
	const page = await person.get("/");
	assert.equal(page.status, 200);
	const { getByRole, getByLabelText, getByTestId } = page.dom;
	assert.equal(getByRole("heading", { level: 1, name: "Notes" }).tag, "h1");
	assert.ok(getByRole("region", { name: "Notes" }), "the section, named by its heading");
	assert.equal(getByTestId("count").text, "3 notes", "the endpoint's answer, read as the page rendered");
	assert.equal(getByRole("status", { name: "Count" }).text, "1");
	assert.equal(getByLabelText("New note").attr("name"), "body");
	assert.deepEqual(page.dom.getAllByRole("button").map((button) => button.name), ["Add one", "Add"]);
	const missing = await person.get("/nowhere");
	assert.equal(missing.status, 404);
	assert.equal(missing.dom.getByRole("alert").text, "404 nothing at /nowhere");
});

A client sends a form in one of two ways:

read reads a GET endpoint as a page reads it, and events reads an endpoint's server-sent events as they arrive:

packages/testing/test/app.test.mjs
test("a form posted without the runtime goes back to its page with a flash; the runtime's gets its answer", { skip }, async () => {
	const person = app.client();
	await person.get("/");
	const posted = await person.post("/notes", { body: "  milk " });
	assert.equal(posted.status, 303);
	assert.equal(posted.location, "/", "back to the page it came from");
	assert.deepEqual(person.flash, { url: "/notes", status: 200, body: '"added milk"' }, "what the page reads: what was typed stays on the server");
	assert.equal((await posted.follow()).status, 200);
	assert.equal(person.flash, null, "the page it landed on let it go");
	…
	const sent = await person.submit("/notes", { body: "eggs" });
	assert.deepEqual([sent.status, sent.json()], [200, "added eggs"]);
…
});
…
test("an endpoint the page reads, an endpoint's JSON, and a stream of events", { skip }, async () => {
	const person = app.client();
	assert.equal(await person.read("/notes"), 3);
	…
	const ticks = await person.events("/api/ticks");
	assert.deepEqual((await ticks.take(4)).map(({ event, data }) => [event, data]), [
		["message", '{"tick":1}'],
		["message", '{"tick":2}'],
		["message", '{"tick":3}'],
		["end", ""],
	]);
});

With no SMTP_URL, the email plugin keeps the last 100 messages in the server's memory instead of sending them, under --debug (which startServer passes) as under --dev. So each test server starts with an empty mailbox. app.mail() reads the messages (each with to, cc, bcc, reply_to, headers, subject, text, html, and the raw message, in which no header names the Bcc); waitForMail waits for one that matches (a list such as cc matches when one of its addresses does); links finds a message's links:

packages/testing/test/app.test.mjs
test("the dev mailbox: what was sent, waited for, and its links", { skip }, async () => {
	const before = (await app.mail()).length;
	assert.equal((await app.client().json("/api/mail", { to: "ada@example.com" })).status, 200);
	const mail = await app.waitForMail({ to: "ada@example.com", subject: "Hello" }, { after: before });
	assert.equal(mail.from, "Notes <notes@example.com>");
	assert.deepEqual(links(mail), ["https://notes.example/hello"]);
	assert.ok(app.logs().some((line) => line.msg === "email: kept, not sent (no SMTP_URL)" && line.to === "ada@example.com" && line.subject === "Hello"), "and the server's log said so");
});

A database, and jobs#

Each test can have its own database, so tests never see each other's rows. The server migrates it as it starts.

Both have sql (a tagged template that escapes its values), query, jobs, enqueue, settleJobs and drop (which removes the database when the test is done).

settleJobs() waits until every due job has run, with the jobs those queued, and answers how each one ended. It doesn't wait for a failed job's later retry; settleJobs({ later: true }) runs retries and jobs queued for later at once, until their attempts are spent. enqueue queues a job as a cron would at its time.

packages/testing/test/app.test.mjs
const person = app.client();
…
assert.equal((await person.json("/api/welcome", { to: "ada@example.com" })).status, 200);
const ran = await db.settleJobs();
assert.deepEqual(ran.map(({ kind, state, input }) => [kind, state, input]), [["welcome", "done", '{"to":"ada@example.com"}']]);
const welcome = await app.waitForMail({ to: "ada@example.com", subject: "Welcome" });
assert.deepEqual(links(welcome), ["https://notes.example/notes"], "its HTML's link");

const id = await db.enqueue("welcome", { to: "bob@example.com" });
assert.deepEqual((await db.settleJobs()).map((job) => [job.id, job.state]), [[id, "done"]]);

// One that fails is tried again later (5 s: the fixture's Job.plugin says `retry_ms`), which a settle doesn't wait for;
// with `later`, it is tried again now, until its attempts are spent.
const failing = await db.enqueue("welcome", { to: "nobody" }, { attempts: 3 });
const first = await db.settleJobs();
assert.deepEqual(first.map((job) => [job.id, job.state, job.attempts]), [[failing, "queued", 1]]);
assert.match(first[0].last_error, /^to nobody: /);
const spent = await db.settleJobs({ later: true });
assert.deepEqual(spent.map((job) => [job.id, job.state, job.attempts]), [[failing, "failed", 3]]);
assert.deepEqual((await db.jobs({ kind: "welcome" })).map((job) => job.state), ["done", "done", "failed"]);

In a browser#

launchBrowser() starts Chromium's headless shell ($CHROME, or Playwright's cached one). With none, it answers null so the test can skip, and the run says so once. In CI (CI set, as GitHub Actions does) or with ROCX_BROWSERS=required, a missing browser is an error, so a broken browser install fails CI instead of skipping its browser tests. ROCX_BROWSERS=optional lets them skip in CI too.

browser.open(url) opens a tab and waits until the page hydrates, strictly: if the server's page isn't what the browser's half renders, it throws. The tab has the same queries; each element found can be clicked, typed in and filled through the browser's own input. findBy… keeps looking until the page shows what it asks for.

packages/testing/test/app.test.mjs
for (const engine of ["chromium", "gecko"]) {
	test(`in ${engine}: the page hydrates strictly, a click and typing change it, and a story is a page`, { skip }, async (t) => {
		const browser = browsers[engine];
		if (!browser) return t.skip(`no ${engine} browser (set ${engine === "gecko" ? "GECKO" : "CHROME"})`);
		const tab = await browser.open(`${app.url}/`);
		try {
			assert.deepEqual(tab.errors, []);
			assert.deepEqual(tab.console, []);
			assert.ok((await tab.requested()).includes("/rocx/app.wasm"));
			await (await tab.getByRole("button", { name: "Add one" })).click();
			const count = await tab.findByText("2");
			assert.deepEqual([count.tag, count.name], ["output", "Count"]);
			const field = await tab.getByLabelText("New note");
			await field.fill("first");
			await field.fill("second");
			assert.equal(await field.value(), "second");
			assert.equal((await tab.findByText("3 notes")).tag, "p");
			await assert.rejects(tab.findByRole("button", { name: "Delete" }, { ms: 100 }), /nothing is a button named "Delete"; the buttons here: "Add one", "Add"/);
		} finally {
			await tab.close();
		}
		const story = await browser.open(`${app.url}${storyPath("Counter", "At ten")}`);
		try {
			assert.equal((await story.getByRole("status", { name: "Count" })).text, "10");
			await (await story.getByRole("button", { name: "Add one" })).click();
			await story.findByText("11");
			assert.deepEqual(story.errors, []);
		} finally {
			await story.close();
		}
	});
}

launchBrowser({ engine: "gecko" }) starts a Gecko browser instead, headless ($GECKO, Zen or Firefox), driven over WebDriver BiDi. Its tabs do what Chromium's do, except take a screenshot in dark mode.

tab.drag(source, target) drags one element onto another as a mouse does, firing dragstart, drag, dragenter, dragover, drop (if the target accepts it) and dragend, each with its coordinates. Chromium uses its own drag and drop. Gecko never finishes a drag that WebDriver starts, so there drag fires the DOM's drag events itself, carrying one DataTransfer. tab.touchDrag(source, target) drags with a finger, with real touch input in both browsers.

Html.to_str can't render a component with signals: its holes need the runtime. Test it through its story: buildForTests(dir, { dev: true }) serves each story as a page, at storyPath("Counter", "At ten"), to fetch or open in a tab.

The JavaScript modules#

Plain .mjs files with no dependencies, each usable alone; index.mjs exports them all. The package's README lists every function and option.

ModuleGives a test
dom.mjs screen(html), or parse(html) and within(node): the queries, each as getBy… (one, or it throws), queryBy… (one, or null), getAllBy… and queryAllBy…. A node has text, attr(name), role, name and hasClass(name)
server.mjs startServer(executable, { statics, database, dev, flags, env }); its client(), with get, post, submit, json, put, read, events and flash; mail(), waitForMail, logs() and stop(); and links, until and storyPath
postgres.mjs testDatabase(): url, query, sql`…${value}` (each value written as a literal), jobs, enqueue, settleJobs and drop, over a small Postgres client of its own
sqlite.mjs testSqlite(): url, path, query, sql`…${value}` (each value a parameter), jobs, enqueue, settleJobs and drop, over node:sqlite
browser.mjs launchBrowser({ engine }), browser.open(url, { strict, cookies, script }): a tab with the queries, findBy…, waitFor, errors, console, screenshot, drag and touchDrag; elements with click, fill, type, press and value
build.mjsbuildForTests(dir, { client, dev, opt }): the app built; its server, and the directories it serves

Status and limits#

Everything above works and is tested: roc test packages/testing/main.roc runs Dom's expects, and node --test runs the JavaScript against a small app it builds, with Postgres and Chromium when they are there. The examples' tests use it too, such as tasks and board.

Not yet (each needs a change outside the package, written up in packages/testing/PROPOSALS.md):

Limits: