Halmurat T.
Halmurat T.

Senior SDET

Home Blog Books ask About

The Dispatch

Weekly QA notes from the trenches.

Welcome aboard!

You're on the list. Expect real-world QA insights — no fluff, no spam.

© 2026 Halmurat T.

Automation 29
  • Selenium
  • Playwright
  • Appium
  • Cypress
AI Testing 68
CI/CD 13
  • GitHub Actions
  • Slack Reporting
QA Strategy 11
Case Studies 9
Blog/AI Testing
AI TestingHalmurat T./September 29, 2026/13 min

Stop Testing the DOM: Generative UI Needs Contract Tests

Filed underai-testing/playwright/llm/ai-agents/framework-design
Stop Testing the DOM: Generative UI Needs Contract Tests

Table of Contents
  • Why do generative UI tests go flaky when nothing changed?
  • What is the actual contract in a generative UI?
  • How do you assert on a render intent in Playwright?
  • The fixture
  • The contract test
  • What does this catch that a DOM assertion doesn’t?
  • How do you test the part that’s genuinely nondeterministic?
  • What I’d do differently
  • Your next step

On this page

  • Why do generative UI tests go flaky when nothing changed?
  • What is the actual contract in a generative UI?
  • How do you assert on a render intent in Playwright?
  • The fixture
  • The contract test
  • What does this catch that a DOM assertion doesn’t?
  • How do you test the part that’s genuinely nondeterministic?
  • What I’d do differently
  • Your next step

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.

§ What your DOM assertion is actually betting on

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?

src/ai/registry.ts
// 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>;
};
[ TIP ]

If you can’t name your render intents, you don’t have a generative UI — you have a chat box with a stochastic dangerouslySetInnerHTML. Building the registry is the testability work. Everything in this post depends on it existing.

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

tests/fixtures/render-intent.ts
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.

tests/ai/refund-panel.spec.ts
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 modeDOM assertionRender-intent assertion
Model picks the wrong toolFails, message uselessFails with tool name diff
Model drops or malforms a propPasses silentlyFails with prop diff
Registry maps the tool to the wrong componentFails, looks like a UI bugFails at the mapping, obviously
Component restyled by a design changeFails (false alarm)Passes — correctly
Model calls two tools instead of oneUsually passesFails 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.
[ WARNING ]

Do not let the nightly eval block merges. The moment a stochastic score can turn a PR red, engineers will add retries to it, and a retried eval is a random number generator with extra steps.

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.

[ NOTE ]

Want more breakdowns like this — the AI-feature failure modes that don’t show up in the framework docs? Grab the weekly QA automation newsletter using the signup just below. No fluff, just patterns from 10+ years of shipping enterprise suites.

§ Frequently Asked FAQ
+ 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.

§ Further Reading 03 of 03
01AI Testing

Your Agent's Confirm Dialog Is Safety Theater

Your Playwright test checks the confirm dialog renders — not that the irreversible action was blocked. Test the human-in-the-loop approval gate properly.

Read →
02AI Testing

Your Agent Acts on Half-Streamed Tool-Call JSON

Streamed tool-call arguments are invalid JSON until the final chunk — here's the Playwright pattern that stops your AI agent from acting on half-parsed args.

Read →
03AI Testing

Test What Your AI Agent Does, Not What It Says

Your AI agent test is green because you asserted on its reply. Assert on the tool calls it makes in Playwright instead — the pattern for agentic features.

Read →

Don't miss a thing

Subscribe to get updates straight to your inbox.

HT

No spam · Unsubscribe anytime

Welcome aboard!

You're on the list. Expect real-world QA insights — no fluff, no spam.

§ Colophon

Halmurat T. — Senior SDET writing about test automation, CI/CD, and QA strategy from 10+ years in the enterprise trenches.

Set in
IBM Plex Sans, Lora, and IBM Plex Mono.
Built with
Astro, MDX, Tailwind CSS & Expressive Code. Served by Vercel.
Privacy
No cookies. No tracking scripts on the main thread — analytics run sandboxed via Partytown.
Source
github.com/Halmurat-Uyghur
Terminal
Try /ask to query Halmurat's notes in a shell prompt.

© 2026 Halmurat T. · Written in plain text, shipped in plain time.

Search
Esc

Search is not available in dev mode.

Run npm run build then npm run preview:local to test search locally.