Frontend Testing Guide (PPP Instance)
This guide covers all frontend testing patterns for the PPP instance: Storybook stories, play tests, component unit tests, and the mocking infrastructure.
Table of Contents
- Running Tests
- Two Test Environments
- Test Categorisation
- Storybook: Dev Server
- Storybook: CLI Testing (Automated)
- Story File Locations
- Writing Stories
- Play Tests
- Container/Presenter Pattern
- Mock Data Strategy
- MockTrpcProvider Pattern
- Component Unit Tests (RTL)
- Common Mistakes to Avoid
Running Tests
All commands run from instances/ppp/:
cd instances/ppp
# Run Storybook tests (browser/playwright)
pnpm test:story
# Run Storybook tests with verbose output
pnpm test:story --reporter=verbose
# Run a specific story file
pnpm test:story --run src/modules/WorkQueue/index.stories.tsx
# Run stories matching a name pattern
pnpm test:story --testNamePattern="WorkQueue"
# Run component unit tests (jsdom)
pnpm test
# Run unit tests with coverage
pnpm test:coverage
# Start Storybook dev server (manual visual inspection only)
pnpm storybookTwo Test Environments
The PPP instance has two separate test environments, each using a different Vitest config:
| | Storybook tests | Unit tests | | ---------------- | ------------------------------------ | ------------------- | --- | --- | ----- | --------------------------- | | Command | pnpm test:story | pnpm test | | Config | vite.config.ts --project=storybook | vitest.config.ts | | Environment | Browser (Playwright/Chromium) | jsdom | | Setup file | .storybook/vitest.setup.ts | src/test/setup.ts | | File pattern | \*_/_.stories.@(js | jsx | mjs | ts | tsx) | **/*.{test,spec}.{ts,tsx} | | Timeout | 60s | default | | Use for | Story play tests | RTL component tests |
Important: Storybook tests run in a real browser (headless Chromium). This means vi.mock() does not work in story files — use MockTrpcProvider instead.
Test Categorisation
Unit vs integration
All frontend tests are unit tests. There is no frontend equivalent of the backend *.integration.test.ts convention. Frontend tests never hit a real server or real database — all network calls are mocked (via vi.mock(), MockTrpcProvider, or MSW in future). If a test would need a live backend it belongs in the BDD E2E suite (instances/ppp/e2e/), not in pnpm test.
Vitest environment: jsdom vs node
The vitest config sets environment: 'jsdom' as the project-wide default. Tests that need DOM APIs inherit this automatically.
For pure-logic files that have zero DOM dependency, you may override to node by adding a docblock comment at the top of the file:
/**
* @vitest-environment node
*/The node environment skips jsdom startup (~50–100 ms per file) and avoids false confidence that browser globals are available.
When to use @vitest-environment node
Use node when the file:
- Tests pure functions (utilities, data transforms, parsers, exporters, date helpers)
- Tests services whose fetch calls are fully mocked (e.g. a future
fhirApi.test.ts) - Tests hooks that have zero browser-API usage — no
document,window,localStorage,ResizeObserver, etc. - Has zero imports from
@testing-library/react,render,screen,fireEvent, oruserEvent
When to keep jsdom (the default — no override needed)
Keep jsdom when the file:
- Tests React components with
render,screen,fireEvent, oruserEvent - Tests hooks that interact with browser APIs (
localStorage,sessionStorage,ResizeObserver,IntersectionObserver,document.title, etc.) - Tests anything that relies on CSS-in-JS (MUI components require
document) - Uses
vi.spyOn(window, ...)orvi.spyOn(document, ...)
Explicit @vitest-environment jsdom annotations
Many existing files carry an explicit @vitest-environment jsdom docblock. These are redundant — the vitest config already defaults to jsdom — but they are kept as self-documenting comments that confirm the file requires the browser environment. Do not remove them on sight; they serve as a "this file intentionally uses the DOM" marker.
New files do not need the annotation unless node is the right choice (in which case annotate @vitest-environment node).
Decision table
| What you are testing | File extension | Environment | Network? |
|---|---|---|---|
| React component | .test.tsx | jsdom (default) | No — mocked |
| React hook using browser APIs | .test.ts / .test.tsx | jsdom (default) | No — mocked |
| Pure utility / data transform | .test.ts | node preferred | No — mocked |
| Pure hook (no DOM) | .test.ts | node preferred | No — mocked |
| Story play test | .stories.tsx | Browser (Playwright) | No — MockTrpcProvider |
| BDD / E2E scenario | .feature + steps | Browser (Playwright) | Only if @requires-backend |
Frontend has no integration test category. A frontend test that needs real network calls should be written as a BDD scenario in
instances/ppp/e2e/bdd/. See the BDD & Feature Graph Workflow section inCLAUDE.mdat the repository root.
Where BDD scenarios actually execute (#11320)
A green BDD-related check does not always mean a scenario ran. The three surfaces are deliberately different, and conflating them is what let a broken assertion merge three times (PR #11304, PR #11316, and a ci-ops scenario that had been red on uat unnoticed):
| Surface | Trigger | Executes scenario bodies? |
|---|---|---|
Validate BDD (type-check + feature graph) | every PR | No — step-definition tsc + feature-graph DAG only |
Validate BDD Scenarios (bounded) | every PR | Yes, bounded: @regression scenarios owning a changed file |
bdd-uat.yml / e2e.yml | nightly / dispatch | Yes, the full suite against a live backend |
The bounded per-PR job runs only the scenarios whose owning .feature file asserts on a file in the PR's diff, excluding @requires-backend (live dependency) and @wip. Ownership is derived from the feature files themselves — a file-assertion scenario names the repo file it reads — so the mapping cannot drift away from the assertion. A changed *.steps.ts resolves via the step expressions it defines, matched against real feature step lines, not by filename: step files are organised by concern rather than by feature, so a name-matching rule would resolve nothing for most of them. It fails loudly rather than passing when it resolves nothing it can explain. See .github/scripts/resolve-bdd-scope.mjs, and .github/scripts/prove-bdd-gate-goes-red.mjs for the executable proof that the gate can go red (the #11004 convention).
A scenario needing a live backend must carry @requires-backend. Without that tag it lands in the per-PR subset, where no server is started, and will fail on its first navigation rather than being quietly skipped.
An authenticating file-level Background: excludes the whole file from the per-PR job, whatever its scenarios are tagged. A Background: Given I am authenticated as … applies to every scenario in the file, so all of them need a live backend even when their own steps are pure filesystem assertions — 49 feature files are in this shape. Such a file is reported as SKIPPED (needs live backend — authenticating Background) rather than silently dropped, because an invisible exclusion is indistinguishable from scope the resolver failed to find. Discovered by execution: timesheets.feature was pulled into a bounded run and died in bdd-role-fixture.ts with TypeError: fetch failed. To bring such scenarios into per-PR coverage, move the auth step out of the Background: into the scenarios that actually need it.
Two execution sets, deliberately different. A feature is run whole when the diff touched the feature file itself or a file its scenarios assert on. A feature pulled in only because a changed *.steps.ts defines expressions appearing inside it is narrowed to just the scenarios that bind those expressions, matched by name. Without the narrow set one step-file edit dragged 219 unrelated scenarios into the run (timesheets.feature alone has 195) and the job hit its timeout — observed live. The name alternation is passed via BDD_SCENARIO_GREP, not --grep: at 98 names it is a 7.2 KB pattern that exceeds the command-line length limit. It narrows the run only; generation is filtered by --tags, so an excluded scenario still generates and is reported as skipped rather than being absent.
For the backend equivalent of this table, see Backend Testing.
Storybook: Dev Server
Use the dev server only for manual visual inspection during development.
cd instances/ppp
pnpm storybook # Starts at http://localhost:6006/Use for: Interactive exploration, design review, developing stories visually.
Do NOT use for: Automated testing — use pnpm test:story instead.
Storybook: CLI Testing (Automated)
pnpm test:story runs vitest --config=vite.config.ts --project=storybook, which executes all story play functions in a headless Chromium browser.
cd instances/ppp
# Run all story tests
pnpm test:story
# Test a specific file
pnpm test:story --run src/modules/WorkQueue/index.stories.tsx
# Test all stories in a directory
pnpm test:story --run src/forms/WBAForm
# Test stories by name pattern
pnpm test:story --testNamePattern="Default"
# Watch mode during development
pnpm test:story src/modules/WorkQueue/index.stories.tsxOnly stories with a play function are actually "tested" — stories without play are rendered but not asserted against. Add play functions to validate behavior.
Story File Locations
Story files live alongside their components, following the Storybook config in .storybook/main.ts:
instances/ppp/src/
├── components/ ← src/components/**/*.stories.tsx
├── modules/ ← src/modules/**/*.stories.tsx
├── forms/ ← src/forms/**/*.stories.tsx
├── hooks/ ← src/**/*stories.tsx (catch-all)
├── slots/ ← src/**/*stories.tsx
├── utils/ ← src/**/*stories.tsx
└── landing/ ← src/**/*stories.tsxFile naming: Co-locate the story with the component it tests:
src/modules/WorkQueue/index.stories.tsx— testsWorkQueueViewsrc/forms/WBAForm/CreateViewUpdateForm.stories.tsx— tests the WBA formsrc/components/CadenceTracker.stories.tsx— testsCadenceTracker
Writing Stories
Imports
import type { Meta, StoryObj } from '@storybook/react-vite'; // ← react-vite, not react
import { expect, within, fn, userEvent, waitFor } from '@storybook/test'; // ← storybook/testMinimal story structure
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, within, fn } from '@storybook/test';
import { Box } from '@mui/material';
import { MemoryRouter } from 'react-router-dom';
import { MyView } from './MyView';
import { MOCK_DATA } from './mocks/myData';
const meta: Meta<typeof MyView> = {
title: 'PPP/Modules/MyModule',
component: MyView,
parameters: {
layout: 'fullscreen',
},
decorators: [
Story => (
<MemoryRouter initialEntries={['/my-path']}>
<Box sx={{ p: 3, minHeight: '100vh' }}>
<Story />
</Box>
</MemoryRouter>
),
],
args: {
isLoading: false,
onItemClick: fn(), // ← fn() from @storybook/test
},
};
export default meta;
type Story = StoryObj<typeof meta>;
export const Default: Story = {
args: { items: MOCK_DATA },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const heading = await canvas.findByText('My Module');
await expect(heading).toBeInTheDocument();
},
};
export const Empty: Story = {
args: { items: [] },
};
export const Loading: Story = {
args: { items: [], isLoading: true },
};Global decorators (already provided by preview.ts)
The .storybook/preview.ts file wraps every story with:
MemoryRouterSnackbarProviderQueryClientProvider(retry: false, refetchOnWindowFocus: false)
You only need to add these in a story-level decorator if you need specific configuration (e.g., initialEntries for routing, or a custom QueryClient).
Story titles
Follow the PPP/[Category]/[Name] convention:
PPP/Modules/WorkQueuePPP/Components/CadenceTrackerPPP/Forms/WBAForm
Play Tests
Play tests run in the browser after a story renders. Use them to assert that the component displays correctly and responds to user interaction.
Imports
import { expect, within, fn, userEvent, waitFor, fireEvent } from '@storybook/test';Basic play test
export const Default: Story = {
args: { items: MOCK_DATA },
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// Wait for async content
const title = await canvas.findByText('Page Title');
await expect(title).toBeInTheDocument();
// Query synchronously once rendered
const rows = canvas.getAllByRole('row');
expect(rows.length).toBeGreaterThan(1);
},
};User interactions
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
// Click
await userEvent.click(canvas.getByRole('button', { name: 'Submit' }));
// Type into input
await userEvent.type(canvas.getByRole('textbox'), 'Hello');
// Select from dropdown
await userEvent.selectOptions(canvas.getByRole('combobox'), 'Option 1');
// Wait for result
await waitFor(() => {
expect(canvas.getByText('Success')).toBeInTheDocument();
});
},Portal/dialog content
MUI Dialogs and Menus render in a portal outside canvasElement. Use document.body:
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const body = within(document.body);
// Open the menu
await userEvent.click(canvas.getByRole('button', { name: 'Open' }));
// Query portal content via document.body
const menu = await body.findByRole('menu');
expect(menu).toBeInTheDocument();
const option = await body.findByText('Menu Item');
await userEvent.click(option);
},Organizing with steps
play: async ({ canvasElement, step }) => {
const canvas = within(canvasElement);
await step('Renders initial state', async () => {
await expect(canvas.findByText('Title')).resolves.toBeInTheDocument();
});
await step('Opens dialog on click', async () => {
await userEvent.click(canvas.getByRole('button', { name: 'Open' }));
const dialog = await within(document.body).findByRole('dialog');
expect(dialog).toBeInTheDocument();
});
},Container/Presenter Pattern
The Container/Presenter pattern enables robust Storybook testing without tRPC mocking.
Reference implementation:
instances/ppp/src/modules/WorkQueue/
Container (index.tsx)
Fetches data via tRPC, handles business logic, wraps with PageLayout.
// src/modules/WorkQueue/index.tsx
const WorkQueueModule = () => {
const { data: items = [], isLoading } = trpcQuery.ppp.workQueue.get.useQuery();
return (
<PageLayout>
<WorkQueueView
items={items}
isLoading={isLoading}
onItemClick={fn()}
/>
</PageLayout>
);
};Presenter (*View.tsx)
Pure UI — no data fetching, no PageLayout.
// src/modules/WorkQueue/WorkQueueView.tsx
export interface WorkQueueViewProps {
items: WorkQueueItem[];
isLoading: boolean;
onItemClick: (item: WorkQueueItem) => void;
}
export const WorkQueueView: React.FC<WorkQueueViewProps> = ({ items, isLoading, onItemClick }) => {
// Pure presentation — no tRPC, no PageLayout
return (
<>
<Box>{/* Header */}</Box>
<Box>{/* Content */}</Box>
</>
);
};Stories test the Presenter, not the Container
// ✅ Correct — import the View (presenter)
import { WorkQueueView } from './WorkQueueView';
const meta: Meta<typeof WorkQueueView> = {
component: WorkQueueView, // Test WorkQueueView, NOT WorkQueueModule
args: {
isLoading: false,
onItemClick: fn(),
},
};When to use Container/Presenter
✅ Use when:
- Component fetches data via tRPC
- Multiple data states to test (empty, loading, error)
- Component is 50+ lines
❌ Skip when:
- Component is already purely presentational
- Component is very simple (< 50 lines)
- No data fetching involved
Layout: keep Presenters layout-agnostic
// ❌ Bad — Presenter includes layout
export const MyView = ({ data }) => (
<PageLayout><Content /></PageLayout>
);
// ✅ Good — layout-agnostic
export const MyView = ({ data }) => <Content />;
// ✅ Container adds layout
const MyModule = () => (
<PageLayout><MyView data={data} /></PageLayout>
);Mock Data Strategy
Centralized mocks
Create a mocks/ directory inside your module:
// src/modules/WorkQueue/mocks/workQueueData.ts
import { WorkQueueItem } from '../config/columns';
export const MOCK_WORK_QUEUE_ITEMS: WorkQueueItem[] = [
{
id: 1,
originator: { id: 101, name: 'John Smith' },
type: 'wba',
wbaType: 'mcr',
createdAt: new Date('2025-01-15T10:30:00Z'),
},
{
id: 2,
originator: { id: 102, name: 'Sarah Johnson' },
type: 'feedback',
wbaType: null,
createdAt: new Date('2025-01-14T14:20:00Z'),
},
];
export const MOCK_EMPTY_WORK_QUEUE: WorkQueueItem[] = [];Keep mocks simple
// ❌ Over-engineered
class MockDataFactory {
static createWorkQueueItem() { ... }
}
// ✅ Simple exported constants
export const MOCK_WORK_QUEUE_ITEMS = [...];
export const MOCK_EMPTY_WORK_QUEUE = [];Mock data defines the API contract
The structure of your mock data is the specification for what the backend must return. If the mock has a field, the API must return it.
MockTrpcProvider Pattern
Use MockTrpcProvider when the Container/Presenter pattern is not feasible — e.g., the component is tightly coupled with tRPC and refactoring is not practical.
Location: src/test-utils/MockTrpcProvider.tsx
Why MockTrpcProvider over vi.mock()?
MockTrpcProvider | vi.mock() | |
|---|---|---|
| Works in browser (Storybook) | ✅ | ❌ crashes |
| Works in jsdom unit tests | ✅ | ✅ |
| Per-story mock data | ✅ | ❌ (module-level) |
| Loading/error states per story | ✅ | ❌ |
| No hoisting issues | ✅ | ❌ |
vi.mock() breaks in Storybook because stories run in a real browser — never use it in .stories.tsx files.
Props
interface MockTrpcProviderProps {
children: React.ReactNode;
mockData?: Record<string, any>; // Mock return values (dot notation paths)
isLoading?: Record<string, boolean>; // Loading state per path
errors?: Record<string, Error>; // Error per path
}Implementation
Step 1: Import and wrap
import { MockTrpcProvider } from 'test-utils/MockTrpcProvider';
import { CadenceTracker } from './CadenceTracker';
const meta: Meta<typeof CadenceTracker> = {
title: 'PPP/Components/CadenceTracker',
component: CadenceTracker,
decorators: [
(Story) => (
<MockTrpcProvider
mockData={{
// dot notation matches tRPC router paths
'core.getCadenceTracker': { id: '123', assessments: { CBD: 5, CEX: 3 } },
'ppp.activity.getActivityCadence': { id: '123', cadence: 'weekly' },
}}
>
<Story />
</MockTrpcProvider>
),
],
};For each path, MockTrpcProvider automatically creates:
useQuery()— fortrpcQuery.namespace.procedure.useQuery()useMutation()— fortrpc.namespace.procedure.useMutation()query()— fortrpc.namespace.procedure.query()
Step 2: Test different states per story
// Loading state — override isLoading for specific query
export const Loading: Story = {
decorators: [
(Story) => (
<MockTrpcProvider
mockData={{ 'core.getCadenceTracker': mockData }}
isLoading={{ 'core.getCadenceTracker': true }}
>
<Story />
</MockTrpcProvider>
),
],
};
// Error state
export const ErrorState: Story = {
decorators: [
(Story) => (
<MockTrpcProvider
mockData={{ 'core.getCadenceTracker': mockData }}
errors={{ 'core.getCadenceTracker': new Error('Failed to load') }}
>
<Story />
</MockTrpcProvider>
),
],
};Key files
| File | Purpose |
|---|---|
src/test-utils/MockTrpcProvider.tsx | React provider — main implementation |
src/utils/trpc-test.ts | Deep proxy utilities |
src/utils/trpc.ts | Main trpc/trpcQuery exports (checks for mocks via proxy) |
When to use MockTrpcProvider vs Container/Presenter
| Scenario | Approach |
|---|---|
| New component with tRPC | Container/Presenter (preferred) |
| Existing tightly-coupled component | MockTrpcProvider |
| Component needs loading/error state testing | MockTrpcProvider (per-story states) |
| Complex refactor not justified | MockTrpcProvider + TODO comment |
Component Unit Tests (RTL)
For unit testing components in isolation with jsdom (no browser required).
Setup
Tools:
- Vitest (
vitest.config.ts) — test runner - React Testing Library — component testing
- jest-dom — DOM matchers (via
src/test/setup.ts)
Writing tests
import { describe, it, expect } from 'vitest';
import { render, screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { MyComponent } from './MyComponent';
describe('MyComponent', () => {
it('renders correctly', () => {
render(<MyComponent title="Hello" />);
expect(screen.getByText('Hello')).toBeInTheDocument();
});
it('handles click', async () => {
const user = userEvent.setup();
const onAction = vi.fn();
render(<MyComponent onAction={onAction} />);
await user.click(screen.getByRole('button', { name: 'Submit' }));
expect(onAction).toHaveBeenCalledOnce();
});
});Common queries (prefer semantic)
screen.getByRole('button', { name: 'Submit' }); // ✅ best
screen.getByText('Hello'); // ✅ good
screen.getByLabelText('Email'); // ✅ good
screen.getByTestId('submit-btn'); // ⚠️ last resortRunning unit tests
cd instances/ppp
pnpm test # all unit tests
pnpm test MyComponent # tests matching a name
pnpm test:coverage # with coverage reportShard Tuning
CI runs the frontend suite across N parallel runners using Vitest's built-in --shard flag. Choosing the right shard count is a balance between parallelism gains and fixed per-runner overhead (checkout + pnpm install + build:pkgs ≈ 2–3 minutes).
Overhead formula
wall_clock ≈ setup_overhead + (test_files / shard_count) × avg_file_timesetup_overhead— ~2–3 min per runner (constant, not reduced by more shards)avg_file_time— ~2–4 s per test file under jsdom
Beyond ~8 shards the per-shard setup overhead dominates test execution time, so adding more shards stops helping.
When to re-evaluate shard count
Re-evaluate when any shard consistently exceeds 6 minutes of test execution time (excluding setup). At ~5–10 new test files per week, expect to revisit every 3–4 months.
| Test file count | Recommended shards |
|---|---|
| < 300 | 4 |
| 300–500 | 6 (current) |
| 500–700 | 8 |
| > 700 | 10 |
Benchmark workflow
A manual + weekly workflow (.github/workflows/test-shard-benchmark.yml) runs the suite with 4, 6, 8, and 10 shards in parallel and posts a timing table to the GitHub job summary. Trigger it from Actions → Frontend Shard Benchmark after adding a large batch of test files to confirm the current shard count is still optimal.
The wall-clock estimate in the summary = sequential total ÷ shard count, which approximates actual parallel execution time assuming equal runner capacity.
Common Mistakes to Avoid
Using vi.mock() in story files
// ❌ NEVER in .stories.tsx — breaks in browser environment
vi.mock('utils/trpc', () => ({ ... }));
// ✅ Use MockTrpcProvider instead
<MockTrpcProvider mockData={{ ... }}>
<Story />
</MockTrpcProvider>Testing the Container instead of the Presenter
// ❌ Tests Container — has real tRPC dependency
const meta: Meta<typeof WorkQueueModule> = { component: WorkQueueModule };
// ✅ Tests Presenter — takes mock props
const meta: Meta<typeof WorkQueueView> = { component: WorkQueueView };Including PageLayout in a Presenter
// ❌ Presenter includes layout
export const MyView = () => (
<PageLayout><Content /></PageLayout>
);
// ✅ Presenter is layout-agnostic
export const MyView = () => <Content />;Creating viewport stories
// ❌ Redundant — use Storybook viewport toolbar instead
export const Mobile: Story = { ... };
export const Desktop: Story = { ... };
// ✅ One story, switch viewports via toolbar
export const Default: Story = { ... };Using @testing-library/react imports in stories
// ❌ Wrong — for jsdom unit tests only
import { expect, within } from '@testing-library/react';
// ✅ Correct — for story play functions
import { expect, within } from '@storybook/test';Using wrong Storybook import
// ❌ Wrong import in this project
import type { Meta } from '@storybook/react';
// ✅ Correct
import type { Meta } from '@storybook/react-vite';Forgetting play tests assertions are async
// ❌ findBy* returns a Promise — must await
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
expect(canvas.findByText('Title')).toBeInTheDocument(); // Wrong: asserting Promise
},
// ✅ Correct
play: async ({ canvasElement }) => {
const canvas = within(canvasElement);
const title = await canvas.findByText('Title');
await expect(title).toBeInTheDocument();
},Quick Reference
Should I create a story?
Does this test something unique?
├─ YES → Can it be tested via toolbar/controls?
│ ├─ YES → ❌ Don't create a separate story
│ └─ NO → ✅ Create story
└─ NO → ❌ Don't createHow many stories?
Start with 3:
1. Default (typical data)
2. Empty (no data)
3. Loading
Then:
- Error state needed? → Add 4th
- Important edge case? → Add 5th
- More than 5? → Question each oneWhich testing approach?
New component with tRPC?
├─ YES → 50+ lines? → ✅ Container/Presenter
│ └─ NO → Already simple enough
└─ NO → Pure component? → Test with props (no MockTrpcProvider)
Existing tightly-coupled component?
└─ Use MockTrpcProvider