Undo, redo, and optimistic UI flows fail in a very specific way: the screen looks right for a moment, the network request is in flight, and then the app has to decide whether to keep the local change, reverse it, or reconcile it with server state. If your test only checks the final DOM, you can miss the exact bug that users feel. If your test only checks internal state, you can make the suite brittle for no real gain.

The practical split is this: verify what the user can see in the browser, and verify what the app sent to the network only where the server contract matters. For undo, redo, and optimistic reconciliation, that distinction keeps tests stable while still catching race conditions, rollback mistakes, and retry bugs.

The goal is not to assert every transient state. The goal is to assert the contract the app exposes at each stage: visible UI, request payloads, response handling, and the final reconciled state.

A small project that exposes the hard parts

A note-taking or kanban-style app is a good training project because it naturally has local edits, server persistence, and visible state changes. Build or use a demo app with these behaviors:

  • Add a note or card locally, before the server responds.
  • Allow undo and redo for the last edit.
  • Persist changes to an API after a short debounce or on blur.
  • Show a saving indicator while the request is pending.
  • Roll back the optimistic update if the API rejects the change.
  • Reconcile local and server state if the server returns a normalized version of the data, such as a trimmed title or reordered card.

A minimal model works well:

  • id, title, updatedAt, clientRevision
  • local undo stack and redo stack
  • save status, for example idle, saving, saved, error

If you want a browser automation project that is worth keeping, this is better than a toy todo list because it forces you to handle request timing and state divergence.

What to verify in the UI versus the network layer

The most important design decision is where to place the assertion.

Concern Verify in UI Verify in network layer
User sees the new title immediately Yes No
Undo removes the last visible change Yes Usually no
Redo restores the visible change Yes Usually no
App sends one save request after debounce No Yes
Request payload matches the edited note No Yes
Saving indicator appears and disappears Yes No
Rejection shows rollback or error state Yes Sometimes yes
Server-normalized title is reflected after response Yes Yes, if contract matters
Local history stack size after several edits Usually no No, unless exposed through UI or API

The test should not peek into framework internals unless the app itself exposes that state to the user. For example, checking a Redux store or component hook makes the test tightly coupled to implementation details. That is rarely worth it for undo and redo flows.

Why brittle state assertions fail here

Brittle assertions usually come from one of these habits:

  1. Asserting exact DOM structure instead of visible behavior.
  2. Waiting for a fixed timeout instead of a specific request or UI signal.
  3. Checking internal state snapshots after every action.
  4. Expecting one render order when the app uses async reconciliation.

Undo and optimistic flows are especially sensitive to these patterns because the UI can pass through several valid intermediate states. For example, the app may show the edited title immediately, then show Saving..., then replace the text with a normalized server value, or keep the optimistic value if the backend echoes it back unchanged.

A stable test asserts the sequence only where the sequence matters, and only through observable effects.

A reproducible Playwright setup

Playwright is a good fit here because it can wait on requests, inspect responses, and assert browser-visible behavior without guessing timing. See the official docs for network interception and auto-waiting.

A sample flow for a note app might look like this:

import { test, expect } from '@playwright/test';
test('undo, redo, and optimistic save reconcile correctly', async ({ page }) => {
  await page.route('**/api/notes/**', async route => {
    const request = route.request();
    if (request.method() === 'PUT') {
      await route.fulfill({
        status: 200,
        contentType: 'application/json',
        body: JSON.stringify({ id: 'n1', title: 'Trimmed title', updatedAt: '2026-01-01T10:00:00Z' })
      });
      return;
    }
    await route.continue();
  });

  await page.goto('/notes/n1');
  await page.getByRole('textbox', { name: 'Title' }).fill('  Trimmed title  ');
  await expect(page.getByText('Saving...')).toBeVisible();

  await expect(page.getByRole('textbox', { name: 'Title' })).toHaveValue('Trimmed title');
  await expect(page.getByText('Saved')).toBeVisible();
});

This example checks the user-facing behavior, not internal component state. The mocked response simulates server reconciliation by returning a cleaned title.

Testing undo and redo as user actions

Undo and redo are best tested as keyboard and toolbar actions, because that is how users trigger them. Use the same observable contract each time:

  • The visible value changes as expected.
  • The redo action becomes available only after an undo.
  • The save request reflects the latest visible state.
  • The app does not duplicate requests for intermediate keystrokes unless that is intended.

A compact example:

await page.getByRole('textbox', { name: 'Title' }).fill('First');
await page.keyboard.press('Control+z');
await expect(page.getByRole('textbox', { name: 'Title' })).toHaveValue('');
await page.keyboard.press('Control+Shift+z');
await expect(page.getByRole('textbox', { name: 'Title' })).toHaveValue('First');

A useful extra check is to verify that undo happens before persistence if the app is supposed to treat the edit as local until commit. If the app persists on every keystroke, then your test should assert the network contract instead, not the exact local keystroke count.

Testing optimistic UI without overfitting to the transient state

Optimistic UI testing is often confused with testing final success only. That misses the main failure mode, which is divergence between local and server state.

A good optimistic UI test covers three phases:

  1. Immediate local update.
  2. Pending request state.
  3. Server response, success or failure.

For success, assert that the optimistic state remains or is reconciled into the final normalized state. For failure, assert that the UI either rolls back or shows a clear error path, depending on product design.

await page.route('**/api/notes/n1', route =>
  route.fulfill({ status: 500, contentType: 'application/json', body: JSON.stringify({ error: 'save failed' }) })
);
await page.getByRole('textbox', { name: 'Title' }).fill('New title');
await expect(page.getByText('Saving...')).toBeVisible();
await expect(page.getByText('Could not save')).toBeVisible();

If the UI rolls back on failure, assert that rollback explicitly. If it keeps the edited text and shows an error badge, do not force rollback in the test. The point is to verify the contract the product chose.

Modeling delayed sync and retries

Delayed sync introduces a different class of bug, where the app queues changes locally and flushes them later. Your test should not rely on a single request completing instantly.

Useful checks:

  • The UI shows offline or unsynced status when the request is delayed.
  • The queued change survives a page refresh only if the product promises offline persistence.
  • Retry logic does not reorder edits incorrectly.
  • The final request contains the last intended value, not an older draft.

You can simulate delay with a paused route and then release it after the UI updates:

let release!: () => void;
const gate = new Promise<void>(resolve => (release = resolve));
await page.route('**/api/notes/n1', async route => {
  await gate;
  await route.fulfill({ status: 200, body: '{}' });
});
await page.getByRole('textbox', { name: 'Title' }).fill('Queued title');
await expect(page.getByText('Saving...')).toBeVisible();
release();
await expect(page.getByText('Saved')).toBeVisible();

This pattern is more reliable than sleeping for a fixed duration, because the test controls the network phase directly.

A decision rule for assertions

Use this rule when you decide where to assert:

  • If the user can see it, assert it in the UI.
  • If the server contract depends on it, assert the request or response.
  • If it is an implementation detail, do not assert it unless the bug history proves it is worth locking down.

That rule keeps tests readable and limits maintenance cost. It also makes failures easier to interpret. A UI failure tells you the user experience broke. A network assertion failure tells you the contract changed.

Failure modes worth covering

A minimal undo, redo, and optimistic reconciliation suite should include these cases:

  • Undo after a local edit, before save.
  • Redo after undo, before save.
  • Undo after the first save request is in flight.
  • Optimistic success with a server-normalized response.
  • Optimistic failure with rollback or error state.
  • Delayed network response, then late success.
  • Two quick edits where only the latest value should persist.

The last case is especially useful for browser automation state assertions, because it exposes stale request handling. If the first request returns after the second, the app should not revert the screen to the older value.

What not to test

Skip these unless your app exposes them directly in the UI:

  • Internal history stack length.
  • Component state snapshots.
  • Framework-specific store shape.
  • Exact number of renders.

Those details change frequently and do not help a user judge whether undo, redo, or reconciliation works. If the app uses a public API for draft history, test the API contract separately, not through browser automation.

A compact checklist for a maintainable suite

Before you add another assertion, check whether the test already covers the contract:

  • Is the current visible value correct after each action?
  • Does the request payload reflect the last intended change?
  • Does the app show pending, success, and error states as designed?
  • Does the final UI match the server response when reconciliation is expected?
  • Does the test avoid private state or fixed timing assumptions?

If the answer is yes to all five, you are probably testing the right layer.

Bottom line

To test undo redo flows in browser automation without brittle state assertions, treat the UI and the network as separate verification surfaces. Use the UI for visible behavior, use request and response checks for server contracts, and ignore internal state unless the product exposes it intentionally. That approach gives you a suite that survives refactors, catches rollback bugs, and still tells you what broke when the test fails.

FAQ

Should undo and redo be tested through keyboard shortcuts or buttons?

Both, if both are supported. Keyboard shortcuts verify accessibility and user muscle memory, while buttons verify discoverability and click handlers. Do not assume one covers the other.

How do I test optimistic UI if the server response is nondeterministic?

Assert the stable parts of the response contract, such as that the item is saved and the final visible state matches the normalized server value. Avoid asserting timestamps or other fields that are expected to vary.

What is the best wait strategy for delayed sync tests?

Wait on a specific network event or visible status change. Avoid fixed sleeps, because they make async reconciliation tests slow and still flaky.

Should I mock the API or run against a real backend?

Mock the API for most undo and optimistic flow coverage, because it gives you deterministic success, failure, and delay cases. Keep a smaller number of end-to-end tests against a real backend for contract confidence.

How do I know if I am over-asserting state?

If a test fails when you refactor a reducer, rename a component, or change a store library without changing user behavior, you are probably asserting internal state instead of observable behavior.