Stop Testing the DOM: Generative UI Needs Contract Tests

Table of Contents
Your app used to render a page. Now it renders whatever the model decided to render. The user types “show me my refunds from March,” the LLM picks a tool, the tool call gets mapped to a React component, and a <RefundTable> streams into the panel — or a <RefundSummaryCard> does, or a paragraph of prose does, depending on how the router felt about the phrasing that particular second. Your Playwright suite, which asserts on a table row, is now a coin flip.
The instinct is to make the assertions looser. That’s the wrong move, and it’s how you end up with a suite that passes while the feature is broken. The right move is to stop treating the DOM as the contract. In a generative UI, the contract is the render intent — the tool name plus the props the model produced — and that’s an object you can assert on with exact equality.
Why do generative UI tests go flaky when nothing changed?
Because the component tree is now a model output, not a code path. In classic UI, a given state deterministically produces a given DOM; you seed data, you assert markup. In generative UI, the model receives a prompt plus a set of tools, decides which tool to call, and the framework maps that tool result to a React component. The DOM is now two nondeterministic hops downstream of your fixture.
And that first hop is not as reliable as the demos suggest. Current tool-calling benchmarks show roughly 90%+ well-formed calls on simple single-turn workloads, dropping to 80–90% end-to-end on multi-step real workflows once selection and argument errors compound. Multi-turn scores fall another 5–10 points versus single-turn for essentially every model. A 92% router in a three-turn conversation is not a 92% feature.
80–90%
End-to-end tool accuracy
Multi-step real workflows, after error compounding
5–10 pts
Multi-turn penalty
Versus single-turn, across models
2 hops
Between fixture and DOM
Tool selection, then component mapping
So a suite that asserts expect(page.getByRole('row')).toHaveCount(3) is silently testing the model’s routing decision, the argument extraction, the component registry, the streaming layer, and the styling — all in one assertion, with one failure message. When it goes red you learn nothing. When it goes green you’ve learned even less.
What is the actual contract in a generative UI?
The render intent: the tool name, the arguments the model produced, and the component the registry maps them to. Everything downstream of that — the markup, the ARIA roles, the pixel layout — is ordinary deterministic React that you already know how to test.
Split the system at that seam and three things become true at once. The routing decision becomes a model eval (nondeterministic, run nightly, scored). The component becomes a unit test (deterministic, run on every commit, free). And the wiring between them becomes a contract test in Playwright: given this render intent, does the app actually mount this component with these props?
// The registry IS the contract. Tests assert against this map,// not against whatever markup RefundTable happens to emit today.export const componentRegistry = { refund_table: RefundTable, refund_summary: RefundSummaryCard, policy_answer: PolicyAnswer,} as const;
export type RenderIntent = { tool: keyof typeof componentRegistry; props: Record<string, unknown>;};How do you assert on a render intent in Playwright?
Emit the intent as a custom DOM event when the panel mounts a component, then capture the event stream in a fixture. You get an ordered list of { tool, props } objects per test — which is a far better oracle than markup, and doubles as the world’s cheapest debugging artifact.
Emit the intent from the render boundary
One useEffect in the component that owns the registry lookup. Fire a CustomEvent with the tool name and the props. Ten lines of production code, and it’s the same hook your analytics team wants anyway.
Capture the stream in a Playwright fixture
addInitScript to buffer the events on window, then read them back after the assertion gate. Do not use page.exposeBinding for this — you want the buffer to survive navigation.
Assert the intent, then assert the component separately
Exact-match the tool and the props you care about. Then, and only then, make one shallow DOM assertion to prove the component actually mounted.
Push routing accuracy into a separate nightly lane
The PR gate mocks the tool call. The nightly eval lets the real model route, and scores it. Never mix them.
The fixture
import { test as base, expect } from '@playwright/test';
export const test = base.extend<{ intents: () => Promise<RenderIntent[]> }>({ intents: async ({ page }, use) => { await page.addInitScript(() => { (window as any).__intents = []; addEventListener('ai:render', (e: any) => (window as any).__intents.push(e.detail)); }); await use(() => page.evaluate(() => (window as any).__intents)); },});The contract test
Note what this test does not do: it never looks at a table row, a heading, or a currency string. Those belong to RefundTable’s own unit tests.
test('a refund tool call mounts RefundTable with the model-extracted range', async ({ page, intents }) => { // Deterministic gate: the model is mocked, so this asserts our wiring, // not the model's judgment. Routing accuracy is scored in the nightly lane. await mockToolCall(page, { tool: 'refund_table', props: { from: '2026-03-01', to: '2026-03-31', currency: 'CAD' }, });
await page.getByRole('textbox', { name: 'Ask' }).fill('show my March refunds'); await page.getByRole('button', { name: 'Send' }).click();
await expect(page.getByTestId('ai-panel')).toHaveAttribute('data-streaming', 'false'); expect(await intents()).toEqual([ { tool: 'refund_table', props: { from: '2026-03-01', to: '2026-03-31', currency: 'CAD' } }, ]); await expect(page.getByRole('table', { name: 'Refunds' })).toBeVisible();});That data-streaming gate is not optional. Generative UI streams, and an assertion that fires mid-stream will happily pass against a half-mounted component — the same mid-stream race that breaks streaming AI text assertions, except now it’s the component tree that’s partial rather than the sentence.
What does this catch that a DOM assertion doesn’t?
Argument drift. This is the failure mode nobody plans for, and it is the one that ships.
At a Canadian fintech I worked with, the assistant panel rendered a refunds table. A prompt-template edit — someone added a line about “showing amounts in the user’s local currency” — caused the model to start omitting the currency prop about one call in twelve. The component defaulted to USD. The table rendered. The numbers were correct integers. Every Playwright assertion passed, because they all asserted on the amount text and the row count, and 4,182 is 4,182 whether it’s dollars or loonies.
It sat in production for nine days. A support ticket found it, not the suite.
A render-intent assertion would have failed on the first run, with a diff that reads - currency: "CAD" and + currency: undefined. That is the entire argument for this post. The DOM is a lossy projection of the model’s output, and the props are where the lie lives.
| Failure mode | DOM assertion | Render-intent assertion |
|---|---|---|
| Model picks the wrong tool | Fails, message useless | Fails with tool name diff |
| Model drops or malforms a prop | Passes silently | Fails with prop diff |
| Registry maps the tool to the wrong component | Fails, looks like a UI bug | Fails at the mapping, obviously |
| Component restyled by a design change | Fails (false alarm) | Passes — correctly |
| Model calls two tools instead of one | Usually passes | Fails on array length |
That fourth row matters more than it looks. A generative UI panel gets redesigned constantly, and a suite that goes red every time a designer changes a heading is a suite people start ignoring — which is how the green tests that hide real bugs get there in the first place.
How do you test the part that’s genuinely nondeterministic?
You score it, you don’t gate on it. Routing — did the model pick refund_table for this phrasing? — is a distribution, not a boolean, and pinning a distribution to a hard assertion in a PR gate produces a suite that fails on Tuesdays for reasons nobody can explain.
Run the routing eval on its own schedule, with the real model, over a phrasing corpus you actually own — 30 to 50 real user utterances per tool, mined from your logs, not invented by an LLM. Score it as pass@k and gate on a threshold with a floor, not on individual cases. If refund_table routes correctly on 47 of 50 phrasings and your floor is 90%, that’s a green build and a ticket, not a broken pipeline. The mechanics of that gate are the same pass@k threshold I use for AI test gates generally, and the mocked-model PR lane is what keeps the fast loop honest.
Two lanes, two contracts:
- PR lane (every commit, mocked model, ~90 seconds): render intents match exactly. Components mount. Props are typed. Zero token spend, zero flake.
- Nightly lane (real model, real routing, scored): routing accuracy per tool, prop-extraction accuracy per field, tracked as a time series. A drop of 6 points overnight is a model change, and you’ll see it before your users do.
What I’d do differently
I’d add the render-intent event on day one, before the first component ships — not as a testing hook, but as a product telemetry primitive. Every team I’ve seen retrofit it spent two sprints untangling components that reached into context and rendered conditionally on the model’s text output rather than on a structured tool result. That’s the real anti-pattern, and it’s not a testing problem: it’s an architecture that has no contract to test.
I’d also resist typing the props as Record<string, unknown> for longer than a week. Zod-validate the tool arguments at the registry boundary and you’ve converted the fintech bug above from a nine-day production incident into a compile-time-adjacent runtime throw. Note that Vercel’s RSC-based streamUI is still flagged experimental, and Vercel itself points production teams at the client-side useChat path — build your contract at the registry, not at the framework’s streaming primitive, and you survive that API churn.
Your next step
Open your assistant panel’s spec file and count how many assertions inspect markup the model indirectly produced. Every one of those is a coin flip dressed up as a test. Pick the single highest-traffic tool in your app, emit a CustomEvent with its name and props at the render boundary, and rewrite one spec to assert on that object instead of on a table row. It’s a 40-minute change, and the first prop diff it catches will pay for the rest of the migration.
What is a render intent in generative UI?
The structured object the model produces that determines what the UI shows: the tool name it selected plus the arguments it extracted. Your framework maps that object to a React component through a registry. The render intent is the real contract between model and UI — the DOM is just a lossy projection of it.
Can Playwright test generative UI at all if the output is nondeterministic?
Yes, by splitting the system. Mock the tool call in the PR lane so the render path is deterministic, and assert the render intent with toEqual. Score the model’s routing separately in a nightly eval using pass@k against a real phrasing corpus. Nondeterminism belongs in a scored lane, never in a merge gate.
Why do DOM assertions pass when the model drops a prop?
Because a missing prop usually falls back to a default instead of crashing. A dropped currency prop still renders a table full of correct-looking integers — and toHaveCount(3) has no opinion about currency. Prop-level bugs are invisible to markup assertions and obvious in a render-intent diff.
Should the routing eval block a pull request?
No. A stochastic score that can turn a PR red will get retried until it’s green, which destroys it as a signal. Track routing accuracy per tool as a time series, alert below a floor, and keep the merge gate deterministic and mocked. See also: why retries don’t fix AI test flake.
