# End-to-end journeys and Storybook as a test layer

The two outer layers: Playwright for a handful of journeys against a real build, Storybook for the visual states of design-system primitives. Open this when setting either up or when deciding which layer a case belongs to.

Sources: https://playwright.dev/docs/test-configuration · https://storybook.js.org/docs/writing-tests/interaction-testing · https://storybook.js.org/docs/writing-tests/integrations/vitest-addon

## 1. Playwright: journeys, not pages

Pick 5–15 flows whose failure would stop the business: sign-up → onboarding → first key action; search → add to cart → pay; the permission-gated admin path. Everything else is cheaper and more stable one layer down.

```ts
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: './e2e',
  fullyParallel: true,
  forbidOnly: !!process.env.CI,
  retries: process.env.CI ? 2 : 0,
  reporter: process.env.CI ? [['html'], ['github']] : 'list',
  use: {
    baseURL: process.env.BASE_URL ?? 'http://localhost:3000',
    trace: 'on-first-retry',
    video: 'retain-on-failure',
  },
  projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'] } }],
  webServer: { command: 'npm run start', url: 'http://localhost:3000', reuseExistingServer: !process.env.CI },
});
```

- Run against a **production build** (`next build && next start`, `vite build && vite preview`), never the dev server.
- Log in once in a setup project and reuse `storageState`:

```ts
// e2e/auth.setup.ts
import { test as setup, expect } from '@playwright/test';

setup('authenticate', async ({ page }) => {
  await page.goto('/login');
  await page.getByLabel('Email').fill(process.env.E2E_USER!);
  await page.getByLabel('Password').fill(process.env.E2E_PASSWORD!);
  await page.getByRole('button', { name: 'Sign in' }).click();
  await expect(page.getByRole('heading', { name: /dashboard/i })).toBeVisible();
  await page.context().storageState({ path: 'e2e/.auth/user.json' });
});
```

- Locators are role-based (`page.getByRole`, `getByLabel`); `test.step()` makes a failure report readable.
- Data isolation: each test creates what it needs through the API and cleans up, or the suite runs against a seeded ephemeral database. Tests that depend on yesterday's data fail on Mondays.
- `retries: 2` in CI only. A test that needs a retry locally is a bug, not a flake.
- Accessibility: one `@axe-core/playwright` scan per key screen, failing on serious and critical violations.

```ts
import AxeBuilder from '@axe-core/playwright';
const results = await new AxeBuilder({ page }).withTags(['wcag2a', 'wcag2aa']).analyze();
expect(results.violations).toEqual([]);
```

## 2. Storybook 10: stories are the test cases

Every `shared/ui` primitive gets a story per visual state: default, hover/focus, disabled, error, loading, long text, RTL. Those stories are the component's specification and they run as tests.

```tsx
// Button.stories.tsx
import type { Meta, StoryObj } from '@storybook/react-vite';
import { expect, fn, userEvent, within } from 'storybook/test';
import { Button } from './Button';

const meta = { component: Button, args: { onClick: fn() } } satisfies Meta<typeof Button>;
export default meta;
type Story = StoryObj<typeof meta>;

export const Disabled: Story = { args: { disabled: true, children: 'Save' } };

export const Clickable: Story = {
  args: { children: 'Save' },
  play: async ({ canvasElement, args }) => {
    const canvas = within(canvasElement);
    await userEvent.click(canvas.getByRole('button', { name: 'Save' }));
    await expect(args.onClick).toHaveBeenCalledOnce();
  },
};
```

Imports come from **`storybook/test`**. The old `@storybook/test` package was removed in Storybook 9 — installing it pulls a stale 8.x.

## 3. Running stories in CI

The Vitest addon turns every story into a Vitest test in a real browser, so stories and unit tests share one runner and one coverage report.

```bash
npx storybook add @storybook/addon-vitest
```

```ts
// vitest.config.ts — the Storybook project
import { defineConfig } from 'vitest/config';
import path from 'node:path';
import { storybookTest } from '@storybook/addon-vitest/vitest-plugin';
import { playwright } from '@vitest/browser-playwright';

export default defineConfig({
  plugins: [storybookTest({ configDir: path.join(__dirname, '.storybook') })],
  test: {
    browser: { enabled: true, provider: playwright(), headless: true, instances: [{ browser: 'chromium' }] },
    setupFiles: ['.storybook/vitest.setup.ts'],
  },
});
```

`@storybook/test-runner` remains the fallback for setups that cannot use the addon (no browser in CI, an unusual bundler) — it is no longer the default path.

Add `@storybook/addon-a11y` and fail the pipeline on violations for the design system; that is the one place where a blanket accessibility gate is affordable.

Reuse the MSW handlers from `src/test/msw/handlers` through `msw-storybook-addon` so a story renders the same payload the component tests use.

## 4. Which layer takes the case

| Case | Layer |
|---|---|
| Every visual state of a primitive | Storybook story |
| A feature screen's behaviour with a faked API | Vitest + RTL + MSW |
| Layout, focus order, drag, `IntersectionObserver` | Vitest Browser Mode |
| Login → checkout → confirmation across pages | Playwright |
| Visual diff of a design-system change | Storybook + a visual-diff service |

If a case fits two rows, take the cheaper one. Duplicated coverage costs maintenance twice and catches the same bug once.
