Guides

Testing with assertions

mx needs no compiler or build step, and neither do its tests. Start with plain JavaScript assertions against the rendered DOM: they check the relationships your app depends on without framework-specific test tooling.

Here you'll build one small pipeline out of a tiny app API, throwing assertions that read the DOM, a headless browser that drives both and a parity gate for rewrites. These checks complement static analysis and unit tests, but they do not replace every kind of validation.

  1. window.__appExpose the app's real verbs
  2. check()Assert invariants from the DOM
  3. HeadlessDrive the verbs in a real browser
  4. Parity gateOld and new must agree

Expose your app's verbs#

Make the app drivable without a mouse. Attach a plain object of the app's real operations - the same functions your event handlers call - to window in dev builds. It is your app's real API rather than test scaffolding added afterwards, and defining it usually improves the design.

These named functions must already exist in your app. Share the mutation functions with your event handlers, and make the observation functions read the DOM. Expose this API only in development or test builds.

JS
window.__app = {
  reset,                   // return to a known state
  addItem,                 // accept a title, update the UI, return its numeric ID
  setFilter,               // accept filter text, then update the UI
  visibleIds,              // read rendered row IDs
  count                    // read the displayed count
};
Synchronous rendering is not synchronous work

For synchronous operations, check the DOM after rendering completes. If an operation fetches data, uses a timer, or schedules work in an animation frame, await its completion or wait for the expected UI state before asserting.

Assert invariants, not snapshots#

Invariants describe relationships that should hold after a mutation: the counter matches the rendered rows, the DOM matches the expected visible items, and a filtered list only contains matches. Choose these checks where they express intent more clearly than a large snapshot.

host is your list container, view() renders it, and expectedVisibleItems() derives the expected filtered items from your model. Define DEV in your development setup. The assertion helper throws, so a failed check stops the operation.

JS
function assert(condition, message) {
  if (!condition) throw new Error(message);
}

function check() {
  let rows = host.querySelectorAll('.row').length;
  let expected = expectedVisibleItems().length;
  assert(rows === expected,
    'DOM rows (' + rows + ') != expected (' + expected + ')');
  let counter = host.querySelector('.counter');
  assert(counter !== null, 'counter is missing');
  assert(counter.textContent === String(rows) + ' shown',
    'counter is stale');
}

// Call it after every render in dev
function update() {
  host.render(view());
  if (DEV) check();
}

Run these checks on the transitions your tests exercise. They catch stale derived values and model/DOM drift wherever an assertion covers it.

console.assert() does not stop anything

console.assert() logs a failed assertion in browsers and carries on. The throwing helper above ends the operation, so the failure reaches your test harness.

Verify at the DOM, not the model#

Asserting on your state object only proves you mutated your state object. The user sees the DOM, so observation methods should read what is actually rendered.

Here host contains only this list, and each .row has a numeric data-id attribute. querySelectorAll() finds the rows, and dataset reads their data attributes.

JS
function visibleIds() {
  // Read rendered rows in document order
  return [...host.querySelectorAll('.row')].map(r => +r.dataset.id);
}

State assertions remain useful for model logic. DOM assertions add coverage for what was rendered.

Virtualized lists

Assert the expected rendered window rather than assuming every matching item has a DOM row.

Drive it headlessly#

A Node ESM script loads the app in a real browser and calls the verbs from the API above. It needs Playwright and its Chromium browser installed and an app running at localhost:8000. The app operations here complete synchronously. Save it as a .mjs file and run it with Node.

check.mjsESM
import { chromium } from 'playwright';

let browser = await chromium.launch();
try {
  let page = await browser.newPage();
  let pageErrors = [];
  page.on('pageerror', error => pageErrors.push(error.message));
  await page.goto('http://localhost:8000/');
  await page.waitForFunction(() => window.__app);

  let result = await page.evaluate(() => {
    let A = window.__app;
    A.reset();
    A.addItem('buy bread');
    let milkId = A.addItem('buy milk');
    A.setFilter('milk');
    return { visible: A.visibleIds(), count: A.count(), milkId };
  });

  if (result.visible.length !== 1 || result.visible[0] !== result.milkId)
    throw new Error('filter returned the wrong item');
  if (pageErrors.length) throw new Error(pageErrors.join('\n'));
  if (result.count !== 1) throw new Error('displayed count is stale');
} finally {
  await browser.close();
}
What this covers

It covers application operations against a real DOM. It does not exercise the click or keyboard bindings themselves, so add browser interactions for those flows. Keep focused unit tests for pure logic and edge cases that are cheaper to exercise separately.

Parity testing across two implementations#

When two implementations should behave identically, drive both through the same operation sequence and compare their observations. This is useful when rewriting an app or comparing builds.

oldApp and newApp are independent, synchronous adapters with reset, setFilter, toggle, visibleIds and count methods. Both fixtures contain item 42. Observations are ordered arrays of numeric IDs and numeric counts.

JS
function assertEqual(actual, expected) {
  if (JSON.stringify(actual) !== JSON.stringify(expected)) {
    throw new Error('Implementations disagree');
  }
}

let ops = [a => a.reset(), a => a.setFilter('auth'), a => a.toggle(42)];

for (let op of ops) {
  op(oldApp); op(newApp);
  assertEqual(oldApp.visibleIds(), newApp.visibleIds());
  assertEqual(oldApp.count(), newApp.count());
}

Compare additional observables when they matter: scroll position, focused element, selection and error state. The operation sequence and the observations determine what this test covers.

Agreement is not correctness

Both versions can share a bug, and intentional behaviour changes need separate expectations.

Development checks in production builds#

A runtime flag such as let DEV = location.hostname === "localhost" can disable checks outside development, but a minifier generally cannot remove that code: the hostname is only known at runtime.

To remove it, configure a build-time constant replacement such as DEV = false with dead-code elimination, or exclude the development module from your production entry point. Verify the generated output.

Without a build step, gated checks remain in the downloaded source.

Why not just add a linter?#

Linters and runtime assertions answer different questions. Linters catch suspicious code and enforce conventions before execution. Runtime assertions check behaviour for the states and paths you exercise. Use the tools that cover your risks without adding unnecessary setup.

Tip
Assert application invariants

Check the relationships that matter to your UI, such as a displayed count matching visible rows.

Tip
Make failures fail the test

Throw for direct checks. When exercising event handlers, configure your browser harness to fail on uncaught page errors too.

Tip
Check accessibility in interaction tests

Verify focus movement, keyboard navigation and dialog dismissal alongside static accessibility checks.

Tip
Keep checks close to the code

Version them with the implementation and keep their assumptions explicit.

A small app can start with a few direct DOM assertions and a browser script. Add linting, unit tests and other checks where they provide useful coverage. mx does not require a particular test stack.