THE REPLACEQA BLOG

How to test SPA navigation with Playwright

Test SPA navigation with Playwright across clicks, direct URLs, refresh and browser history, checking both the route and rendered content.

To test navigation in a single-page application, verify both the URL and the content after each route transition. Then reach the same route through a direct request, a refresh and browser history. A route that works after clicking inside the app can still fail when a customer opens a bookmark.

This guide uses a small fictional workspace with /spa and /spa/reports. Its downloadable fixture separates client-rendering defects from server fallback defects, making it possible to see which checks catch each problem.

Give each route an observable contract

For our fixture, /spa must show the heading “Workspace” and /spa/reports must show “Reports.” An unknown route must show “Page not found.” The Reports link must take a visitor from the workspace to the reports screen.

Those simple expectations support a useful matrix:

Entry modeActionExpected result
Internal linkClick Reports from the workspaceReports URL and heading
Direct entryOpen /spa/reports in a fresh pageSuccessful document response and Reports heading
RefreshReload the reports routeReports remains available
BackReturn after opening ReportsWorkspace URL and heading
ForwardMove forward againReports URL and heading
Unknown routeOpen /spa/missingDesigned missing-page state

This is a route-entry matrix, not an exhaustive product test. A real Reports page might also need checks for the correct account, filter and data. Keep those requirements explicit instead of treating the heading as sufficient for every application.

Check the destination after an internal click

Extract the runnable example package, then run:

npm ci
npx playwright install chromium
npx playwright test tests/navigation.spec.js

The test configuration starts the fixture automatically. Its internal-link check is:

test('internal link renders its destination', async ({ page }) => {
  await page.goto('/spa');
  await page.getByRole('link', { name: 'Reports', exact: true }).click();
  await expect(page).toHaveURL(/\/spa\/reports$/);
  await expect(page.getByRole('heading', { name: 'Reports', exact: true })).toBeVisible();
});

The two assertions matter independently. A router can update the address bar while leaving the old screen visible. Conversely, a component can render the right heading while leaving the browser at the wrong URL. Checking both catches these mismatches.

The fixture's stale-route fault deliberately updates history without rendering the new screen. In the local Playwright Test 1.63.0 run, the URL assertion passed and the Reports heading assertion failed. You can reproduce that result with Linux/macOS shell syntax:

DEMO_FAULT=stale-route npx playwright test tests/navigation.spec.js --grep 'internal link'

This is a more specific check than requesting the route with an HTTP client. The uptime and journey comparison explains that distinction.

Test direct entry and refresh separately

Client navigation may never ask the server for a new HTML document. Direct entry and refresh do. That creates a deployment dependency which a click-only test can miss.

Our fixture expects a successful document response for the Reports route:

test('direct entry and refresh render the route', async ({ page }) => {
  const response = await page.goto('/spa/reports');
  expect(response?.status()).toBe(200);
  await expect(page.getByRole('heading', { name: 'Reports', exact: true })).toBeVisible();
  const refreshed = await page.reload();
  expect(refreshed?.status()).toBe(200);
  await expect(page.getByRole('heading', { name: 'Reports', exact: true })).toBeVisible();
});

The deep-link fault removes the server's handling of nested routes. The client-side link can still update the screen after loading /spa, but a direct request for /spa/reports returns 404. The direct-entry test caught that response during local validation:

DEMO_FAULT=deep-link npx playwright test tests/navigation.spec.js --grep 'direct entry'

Adapt the status expectation to your actual routing contract. Applications can have redirects, server-rendered routes and different missing-page behavior. Do not configure every path to return 200 just to satisfy this sample.

Run these checks against the built application and its deployment server as well as during development. A development server's automatic fallback can conceal a missing production rule. The included fixture is plain HTML and JavaScript served directly by its Node process; it has no development-server fallback doing extra work behind the example.

Exercise history as a user would

After opening Reports, the history test calls page.goBack() and checks the workspace URL and heading. It then calls page.goForward() and checks Reports again. This catches a router that responds to link clicks but fails to render when the active history entry changes.

Keep the starting page deliberate. Opening Reports directly and pressing Back may leave the application entirely; that is a different journey from going Workspace → Reports → Back. The packaged test creates the history entries it expects to navigate.

The unknown-route test checks the fixture's “Page not found” heading. Decide separately what status code your deployed app should return for that route. A visible missing-page state and an HTTP 404 are related but distinct requirements.

The healthy fixture passed all four tests: internal navigation, direct entry with refresh, history navigation, and the unknown-route state. The broken variants failed the targeted checks described above. The archive's evidence.json contains the recorded results.

Avoid hiding readiness problems with sleeps

Some applications render enabled controls before their event handlers are ready. A fast browser test may click successfully while the application ignores the action. A fixed delay can make that failure harder to reproduce without correcting the user's experience.

Playwright's navigation guide discusses this hydration problem and the distinction between loading a document and an interactive application. If a control cannot work yet, make the application's readiness state honest, and wait for an observable condition appropriate to the task.

The downloadable fixture does not simulate hydration; its defects concern route rendering and server entry. Treat hydration as a separate investigation if the trace shows a valid-looking control whose action has no effect.

For routes that display changing records, also verify that the destination belongs to the selected item. The dynamic-content guide explains how to preserve that relationship without hardcoding an editorial title.

ReplaceQA can discover and validate public journeys during its closed beta. Request access if you want help identifying transitions worth testing, while keeping unvisited routes and additional browser requirements visible in your coverage plan.

Keep checking your important customer journeys.

Explore ReplaceQA ↗