qat

Testing

qatjs test runs your tests in Vitest with no config file: .qx and .tsx components compile as they do in qatjs dev, the document is happy-dom, and @qatjs/test holds the test helpers.

shell3 lines
npm i -D vitest happy-dom @qatjs/test
qatjs test            # once
qatjs test --watch    # on every save

Every test on this page runs against examples/shop: packages/toolchain/test/docs-testing.test.ts writes each one into a copy of the shop, under the name on its first line, and runs it with qatjs test.

qatjs test takes Vitest's usual test files (*.test.ts, *.spec.js, …) except under e2e/, where Playwright's specs live. With a vitest.config.* of your own, that config decides instead.

Reactive-graph tests: what one action updates

In Qat a component runs once. After that, an action updates only the nodes that show what it changed. @qatjs/test turns that into an assertion. render() mounts a component, and each action returns what it did: the elements whose text, attributes or children changed, and how many effects ran.

TypeScript11 lines
// src/components/likes.test.ts
import { expect, it } from 'vitest'
import { render } from '@qatjs/test'
import Likes from './likes.qx'

it('a like updates its count, and runs the effect that reads it', () => {
  const r = render(Likes)
  const u = r.click('.likes button')
  expect(u).toUpdate(['.likes .count'])
  expect(u).toRunEffects(1)
})

toUpdate holds the action to exactly those nodes: no more, no fewer. A target is a selector (.count, li:last-child), the name of a bound node in the program graph (total), or an element. If a change makes one click re-render a whole list, the test fails. The failure lists each node that was updated and not expected, and each node expected and not updated, with its graph id:

3 lines
expected the action to update exactly ul.lines, .total
updated, not expected:
  + <h1> "Cart" (src/pages/cart.tsx#Cart.<h1>)

This catches the "one click updates 500 nodes" regression in a unit test, long before a profiler would. The control the user acted on is not counted as updated by its own value: typing in an input is the user's change, not a re-render.

A store is read the same way. The page shows the lines and the total; removing a line updates those two, and nothing else on the page:

TypeScript13 lines
// src/pages/cart.test.ts
import { expect, it } from 'vitest'
import { render } from '@qatjs/test'
import { cart } from '../stores/cart.js'
import Cart from './cart.tsx'

it('removing a line updates the lines and the total, nothing else', () => {
  cart.add({ id: '1', name: 'Kettle', price: 40 }, 2)
  cart.add({ id: '2', name: 'Teapot', price: 25 })
  const r = render(Cart)
  expect(r.click('.lines li:last-child .remove')).toUpdate(['ul.lines', '.total'])
  expect(r.q('.total').textContent).toContain('80')
})

Actions

Action Does
r.click(t), r.input(t, value), r.change(t, value), r.keydown(t, key), r.focus(t), r.submit(t) A user event on the target
r.act(() => …) A change the test makes itself (cart.add(item))
await r.settle() What async work (a handler's await, a timer) changed since the last action
await r.resolve('api.pay', value), await r.reject('api.pay', error) Answer a mocked call
await r.navigate('/orders') Go to a route with the app's router
r.unmount() Dispose the component: what its cleanups changed

r.mounted.effects counts the effects that ran while it mounted.

Loads and API calls

Pass the objects your component calls as mock. Each of their functions then returns a promise that waits for the test to settle it:

TypeScript16 lines
// src/pages/checkout.test.ts
import { expect, it } from 'vitest'
import { render } from '@qatjs/test'
import '../routes.js'
import { api } from '../contract/index.ts'
import Checkout from './checkout.qx'

it('the order waits for the API, the button disabled meanwhile', async () => {
  const r = render(Checkout, {}, { mock: { api } })
  r.input('input[name="email"]', 'ada@example.com')
  r.input('input[name="name"]', 'Ada')
  r.input('input[name="zip"]', '12345')
  r.submit('form.checkout')
  expect(r.pending()).toEqual(['api.orders.create'])
  expect(r.q('button.btn').hasAttribute('disabled')).toBe(true)
})

The mock is undone with the unmount. (The page reads the router, so the test imports the route table first, as the app does.)

Replay a failure

Every action is recorded. r.sequence() returns the actions as a sequence (v1), the format that qatjs replay opens in a browser and qatjs repro runs again in happy-dom (debug):

JavaScript1 line
writeFileSync('bug.json', JSON.stringify(r.sequence()))

Golden state tests: every state, rendered

A component can be in many states: open or closed, each tone, size and variant, a request pending, answered or failed. golden() finds them for you, from the program graph's value domains:

  • each state whose value is a boolean, a union's member or null;
  • each prop you did not pass whose declared type is finite (size?: 'sm' | 'md' | 'lg', disabled?: boolean);
  • each mocked call (mock) as pending, answered and failed.

It renders every combination, up to limit (64, with a warning above it). It holds each one's DOM to a snapshot named by the state that produced it:

TypeScript10 lines
// src/ui/input/search.test.ts
import { expect, it } from 'vitest'
import { golden } from '@qatjs/test'
import { SearchField } from './input.qx'

it('every state of the search field', async () => {
  const g = await golden(SearchField, { props: { label: 'Search' } })
  expect(g.dimensions).toEqual(['prop:size', 'prop:disabled'])
  expect(g.count).toBe(12)
})

An optional prop counts its absence as one more value: four sizes (sm, md, lg, none) times three for disabled (true, false, none) are the twelve states. A change shows as a diff for each combination that changed, named by its state: SearchField {"prop:size":"lg","prop:disabled":true}. When the change is the one you meant, qatjs test --update accepts it. states: [{ open: true }] replaces the automatic set with the ones you name; extra: [...] adds to it; answers: { 'api.stats': data } is what an answered call returns.

This is how @qatjs/ui covers its visual states: 940 states over 69 components (packages/test/test/ui-golden.test.ts), with no stories to write. In the editor, a component that has golden states shows golden states (n) above it, and the lens opens their snapshots.

Invariants and exploration: rules, not sequences

A test checks the sequences you thought of. A race is the one you did not: a second submit while the first is out, an answer that arrives after the dialog closed, a timer that fires for a state it was not set for. Write the rule instead, where the state is:

.qx15 lines, 1 reactive nameOpen in the playground
import { api } from './api.js'

export default function Save() {
  let saving = state(false)
  async function save() {
    saving = true
    try {
      await api.save({})
    } finally {
      saving = false
    }
  }
  invariant(!saving || document.querySelector('.spin'), 'a spinner while saving')
  return <button class="save" on:click={save} disabled={saving}>Save</button>
}
saving state

invariant(condition, message) is a macro: no import is needed in .qx (import { invariant } from '@qatjs/core/invariant' in .tsx). What happens to it depends on where it runs:

  • qatjs dev: checked after each change, once the change's handler has returned. A broken rule is a QX-INVARIANT error in the overlay.
  • @qatjs/test: checked after each action. A broken rule fails the test.
  • qatjs check --explore: the property the explorer searches against.
  • qatjs compress: the rule is removed. Nothing of it ships.

In the condition, now() is the time, which the explorer controls; a load's pending is its loading. A rule that reads what no event changes is QX-INVARIANT-UNMODELED, a warning, with its own gutter mark in VS Code. Above, the first rule reads the document: the explorer evaluates it, but no event it drives changes document.querySelector. Read a state, a derived, a load, a form or a store field instead.

qatjs check --explore

shell3 lines
qatjs check --explore              # every component with rules; Markdown
qatjs check --explore --json       # { schema: 1, components, diagnostics, written }
qatjs check --explore --only src/pages/checkout.qx --depth 5 --walk 10

For each component with rules, it searches the event orders that break one. It reads the .qx, .tsx and .jsx files under the app's src/, and explores each exported component that has invariant() rules; with none, it says so (explored 0 components: …). Each sequence runs in the real runtime, in happy-dom:

  • Events: each element with an on: handler (one row of a list per handler), with a value its field accepts; each call the component awaits from your modules, answered ok or failed, in any order, late after an abort; the next timer; the unmount; and a kept page's suspend and restore.
  • Search: every sequence up to depth 5, a state seen before not expanded again; then a random walk. At most 15 s for a component.
  • Rules: evaluated after every step.

What a component is explored with comes from the app: the calls it awaits are mocked, and a route page gets its route's load as data.

  • A call answered "ok" gets what your own function returns, called at that moment. The explorer chooses the order, your module gives the value.
  • The network is the explorer's, in every run. fetch and XMLHttpRequest are calls like any other (response fetch GET /api/search ok): ok is a 200 with your function's or null's JSON, and failed is a network error. WebSocket and EventSource connect to nothing: the page is offline. No request reaches a server. A request made outside a run (when a module loads, or after its component is gone) is refused, and the component's exploration stops with QX-EXPLORE-UNMOCKED.
  • Rules are checked once more after the unmount: unmount(() => (alive = false)); invariant(alive || !armed, 'no timer outlives the component') is how to say that nothing the component started outlives it. A component that asks the policy (can(), from its file or one it imports) is explored once per role in policy.json, with that role's permissions: src/pages/orders.qx#Orders as clerk. A finding names its role (as clerk: 'rule' breaks after …), and its generated test (orders-clerk-1.test.ts) replays as that role.

A finding is real: it ran. It is minimized to the shortest sequence that still breaks the rule, and explained in signal terms. This is what the explorer found in the shop's checkout:

6 lines
src/pages/checkout.qx:36:1 error QX-INVARIANT-VIOLATED 'one order at a time' breaks after
  input input[name="email"] = "ada@example.com" → input input[name="name"] = "xx" →
  input input[name="zip"] = "11111" → submit form.checkout → submit form.checkout:
  at step 5 (submit form.checkout); `Checkout.placing` = 2 since step 5; waiting: api.orders.create, api.orders.create
  fix: the action runs again while its request is out: disable the control while it is pending, or ignore the second
  test: tests/explore/checkout-1.test.ts

The button was disabled while submitting, but Enter in a field submits the form anyway, and the order was placed twice. The cause was in @qatjs/form itself, so every form had it: its submit() now ignores a submit while one is pending, and the checkout explores clean. Each finding writes two files:

  • tests/explore/<component>-<n>.test.ts replays the sequence and asserts the rule. It fails while the bug is there and passes once it is fixed.
  • <component>-<n>.json is the sequence (v1), which qatjs replay opens in the browser.

The fix names a known pattern when it sees one: a cleanup missing on dispose, a stale response not discarded, a failure that leaves its state behind, a timer that outlived its state, a double submit.

An absence of findings is bounded by the depth and the walk. It is not a proof. A large page may not finish the search at depth 5 within its 15 s; the report says so (capped).

explore() in a test

The explorer is a function of @qatjs/test too. The checkout's rules, held in a test:

TypeScript12 lines
// src/pages/checkout.explore.test.ts
import { expect, it } from 'vitest'
import { explore } from '@qatjs/test/explore'
import routes from '../routes.js'
import { api } from '../contract/index.ts'
import Checkout from './checkout.qx'

it('no order of events breaks the checkout’s rules', async () => {
  const r = await explore(Checkout, { mock: { api, routes }, only: { api: ['orders.create'], routes: ['navigate'] }, walk: 500 })
  expect(r.rules.map((x) => x.message)).toEqual(['one order at a time', 'submitting only while an order is being placed', 'the cart is empty once the order is placed'])
  expect(r.findings).toEqual([])
})

only limits a mocked object to the calls named: the rest of the router stays itself. replay(Comp, sequence) runs one sequence and returns the rules it broke.

Impact in pull requests

qatjs check --impact <ref> builds the app at <ref> and as it is now. It prints what the change reaches. That is reach, not breakage, which qatjs check reports.

  • For each changed file: the components that render it, the parents that listen to its events, the readers of its signals and store fields, and the modules and federation exposes that import it. All of this comes from the program graph.
  • The routes whose chunk set or size changed, with the size before and after.
  • For a static site, the pages whose links changed. A change outside the app (its toolchain, a package) shows here too, in what each page is built to.
shell2 lines
qatjs check --impact main            # Markdown
qatjs check --impact main --json     # { schema: 1, files, routes, pages }

.github/actions/impact posts it as one comment on a pull request, edited on each push. Check out with fetch-depth: 0, so that the base is in the history.

Before the tests: the state flow of a React app

A React app being moved to Qat has its state in Contexts, slices and props passed down. qatjs migrate --map draws that flow and proposes the Qat shape (a store(), provide/inject, component state) before the code is converted, so that the converted code has its tests' shape from the start. See migrate.

Messages

When the app has locales/, qatjs test serves its catalogs to @qatjs/core/i18n, so t() reads the messages it would read in qatjs dev. Outside qatjs test, call messages() from @qatjs/test before importing a component that reads t(). It takes compiled catalogs, locale → key → message. A message without parameters compiles to itself, so messages({ en: { 'cart.title': 'Cart' } }) works as it is. A message with ICU parameters ({count, plural, …}) has no public compiler: test such components under qatjs test, which compiles locales/ itself.