Skip to content

Testing

Test a route table at the smallest boundary that can prove the behavior. Pure matching needs no DOM; initial rendering needs a location; native navigation needs real events and commit ordering. A fixed memory adapter can select a page, but cannot prove that clicking a link navigates.

The examples use an existing React/TypeScript application, such as the quickstart, and Vitest. Add the test runner:

Terminal window
npm install --save-dev vitest

Create src/matcher.test.ts with a complete test of precedence and captures:

import { expect, it } from 'vitest'
import { createMatcher } from '@studiolambda/router'
it('opens the creation page instead of treating new as a lesson slug', () => {
const matcher = createMatcher<string>()
matcher.register('/lessons/:slug', 'detail')
matcher.register('/lessons/new', 'create')
expect(matcher.match('/lessons/new')).toEqual({ handler: 'create', params: {} })
expect(matcher.match('/lessons/routing')).toEqual({
handler: 'detail',
params: { slug: 'routing' },
})
expect(matcher.match('/missing')).toBeNull()
})

The test proves that a static pattern wins even when registered after the parameter pattern. It does not mount React or exercise a browser navigation.

Create src/router.test.tsx. This complete test uses the React server renderer, so no DOM environment is needed:

import { expect, it } from 'vitest'
import { renderToString } from 'react-dom/server'
import {
createMemoryNavigation,
createRouter,
Router,
useParams,
} from '@studiolambda/router/react'
function LessonPage() {
const { slug } = useParams()
return <h1>Lesson: {slug}</h1>
}
it('renders the lesson selected by the initial pathname', () => {
const matcher = createRouter((route) => {
route('/lessons/:slug').render(LessonPage)
})
const navigation = createMemoryNavigation({
url: 'https://example.com/lessons/routing?view=notes',
})
const html = renderToString(<Router matcher={matcher} navigation={navigation} />)
expect(html).toContain('routing')
expect(html).not.toContain('Not Found')
})
it('does not render protected content when a synchronous initial guard denies access', () => {
const matcher = createRouter((route) => {
route('/private')
.guard(() => {
throw new Error('access denied')
})
.render(LessonPage)
})
const navigation = createMemoryNavigation({ url: 'https://example.com/private' })
expect(() => {
renderToString(<Router matcher={matcher} navigation={navigation} />)
}).toThrow('access denied')
})

Run the two files from your application root:

Terminal window
npx vitest run src/matcher.test.ts src/router.test.tsx

You should see three passing tests. Each test owns a fresh matcher and fixed location, so speculative caches and session closures do not leak across tests. Server rendering creates no client root or event subscription to unmount.

For async initial checks, use a streaming renderer and await readiness, or a client renderer with an ancestor error boundary. renderToString does not wait for a pending guard; asserting its fallback cannot prove that protected content eventually renders or denial reaches your error UI.

Do not mistake a memory result for navigation

Section titled “Do not mistake a memory result for navigation”

createMemoryNavigation never changes its URL and never dispatches events. Its navigate, back, forward, and traverseTo promises resolve to the same entry. Asserting that those promises resolved only proves the fixed adapter returned its placeholder result.

Use it for initial params, search reads, middleware nesting, not-found UI, and initial checks. For interactive rendering tests, register a real test page through createRouter and mount <Router matcher={matcher} navigation={adapter} />; Router has no children slot for a test component.

An event-capable test double must supply more than navigate: spy(). It must dispatch native-shaped events, retain mutable destination/current-entry state, and implement the phase ordering that the test claims to prove. For cancelable events, run precommit before commit and handler after commit. For noncancelable events, commit first and do not allow a precommit callback. Model redirects changing the destination of the same event, not creating a second one.

Keep these doubles in your application test utilities, not production code. Own cleanup of React roots, DOM nodes, observers, and listeners. When a test only spies on a request, it proves dispatch intent, not that the backend accepted or authorized a request.

Use your browser test runner against a built/served application in a Navigation-API-capable browser. Cover observable outcomes rather than assuming a test DOM implements browser navigation:

  • Open a deep link directly and refresh it; verify the expected page and server response.
  • Follow a link and use browser Back/Forward; verify URL, heading, and active-link attributes.
  • Deny a cancelable navigation; verify prefetch/action/content do not run.
  • Deny an interceptable noncancelable traversal; verify the UI stays old even if the URL has committed.
  • Follow a redirect chain; verify target params, guards, and final content without rendering the abandoned page.
  • Submit GET, native POST, and opted-in POST forms; verify who receives the body and whether an action runs.
  • Abort a slow action; verify the UI reports failure without assuming a server mutation was undone.
  • Trigger hover/viewport prefetch; verify expected failure handling and pathname deduplication.

Mocks can establish your code’s reaction to a modeled event, but only native-browser coverage establishes that your supported browser emits and accepts those operations. Keep server permission and CSRF tests independent: passing router tests does not establish backend security.