{"data":{"slug":"github-microsoft-playwright-packages-playwright-core-src-tools-skills-playwright-component-testing-431dddb015c6","title":"Component Testing with Playwright","summary":"Test React or Vue components in isolation using Playwright's built-in mount fixture. The test runs against a story gallery page hosted by the app's own dev server. No extra test runner, bundler integration, or npm packages are required.","url":"https:\/\/skillshunter.net\/skills\/github-microsoft-playwright-packages-playwright-core-src-tools-skills-playwright-component-testing-431dddb015c6","json_url":"https:\/\/skillshunter.net\/api\/public\/v1\/skills\/github-microsoft-playwright-packages-playwright-core-src-tools-skills-playwright-component-testing-431dddb015c6","markdown_url":"https:\/\/skillshunter.net\/skills\/github-microsoft-playwright-packages-playwright-core-src-tools-skills-playwright-component-testing-431dddb015c6.md","download_url":"https:\/\/skillshunter.net\/skills\/github-microsoft-playwright-packages-playwright-core-src-tools-skills-playwright-component-testing-431dddb015c6\/download","category":{"slug":"software-development","name":"Software & Development"},"editor_note":"Implement the gallery page at `<project>\/playwright\/gallery\/` that renders the requested story into `#root`. Start from the worked example in the spec and the framework notes in `references\/react.md` \/ `references\/vue.md`. Keep story discovery (`import.meta.glob`) and the framework mount here \u2014 this is the only framework-specific glue, so keep it small. Import the app's global CSS the same way the app's own entry does.","instructions":"---\nname: playwright-component-testing\ndescription: Set up component testing with Playwright using a story gallery \u2014 scaffold stories and a gallery dev page driven by the built-in mount fixture, no dedicated component-testing runtime. Use when asked to test React or Vue components in isolation with Playwright, or to migrate off @playwright\/experimental-ct-react \/ -vue.\n---\n\n# Component Testing with Playwright\n\nTest components with regular Playwright e2e tests against a small **story gallery** page hosted by the app's own dev server. No extra test runner, bundler integration or npm packages are required.\n\n## Concept\n\n- A **story** is a tiny wrapper component that embeds the component under test in one specific scenario: hard-coded props, mock data, providers, recorded callbacks. Stories live next to the component in `*.story.tsx` (or `.ts`\/`.jsx`\/`.js`\/`.vue`) files; each named export is one story.\n- The **gallery** is a single page you implement to `references\/gallery-spec.md`: it exposes `window.mount(params)` \/ `window.unmount()` that render a story \u2014 resolved from your story files (e.g. with `import.meta.glob`) \u2014 into `#root`. It is framework-specific and yours to own \u2014 there is no template to copy for it.\n- Tests are plain Playwright tests. The built-in **`mount(storyId, props?)` fixture** (from `@playwright\/test`) drives the gallery's `window.mount` and returns a `Locator` for the gallery root (`#root`). Scope the queries from there \u2014 `component.getByRole('button').click()`, not `component.click()`. Nothing to scaffold for it.\n\nEverything the component needs must be set up *inside the story* (it runs in the browser); everything the test asserts must be observable *through the page* (DOM, URL, network). Where the component takes callbacks, the story creates the state, provides the callbacks and records the state into a hidden form for the test to assert on. `mount(id, props)` passes plain serializable `props` to the story.\n\n## Setup workflow\n\n1. **Detect the framework and bundler.** React vs Vue decides the framework notes and example story to follow. Then:\n   - **App runs on Vite** (has `vite.config.*`): the gallery is served by the existing dev server at `\/playwright\/gallery\/index.html` \u2014 Vite serves any `.html` file under the project root, the app's plugins\/aliases\/CSS apply automatically, and `vite build` ignores it. No extra server needed.\n   - **Anything else** (Next.js, webpack, no dev server): run a small standalone dev server (e.g. Vite) that serves the gallery page, and point `baseURL` at it. Requires `vite` and the framework plugin as devDependencies.\n2. **Implement the gallery** to `references\/gallery-spec.md`: a page at `<project>\/playwright\/gallery\/` that renders the requested story into `#root`. Start from the worked example in the spec and the framework notes in `references\/react.md` \/ `references\/vue.md`. Keep story discovery (`import.meta.glob`) and the framework mount here \u2014 this is the only framework-specific glue, so keep it small. Import the app's global CSS the same way the app's own entry does.\n3. **Configure Playwright** \u2014 add to `playwright.config.ts`:\n\n   ```ts\n   projects: [\n     {\n       name: 'components',\n       testDir: '.\/tests\/components',\n       use: { ...devices['Desktop Chrome'], baseURL: 'http:\/\/localhost:5173\/playwright\/gallery\/index.html', serviceWorkers: 'block', reuseContext: true },\n     },\n   ],\n   webServer: {\n     command: 'npm run dev',                                       \/\/ or: npx vite --config playwright\/vite.config.ts\n     url: 'http:\/\/localhost:5173\/playwright\/gallery\/index.html',   \/\/ standalone server: http:\/\/localhost:3100\/playwright\/gallery\/index.html\n     reuseExistingServer: !process.env.CI,\n   },\n   ```\n\n   Match the port to the dev server. `mount` navigates to `baseURL`, so set `baseURL` to the gallery's URL. `serviceWorkers: 'block'` keeps the app's own service worker from serving cached responses that would shadow your `page.route()` mocks. `reuseContext: true` reuses the browser context across tests in a worker (as the old component-testing runtime did) \u2014 a large speedup for component suites. If the config already has projects\/webServer, merge instead of replacing.\n4. **Write a first story** next to an existing component, modeled on `templates\/<react|vue>\/Button.story.*`.\n5. **Write a first spec**, modeled on `templates\/react\/button.spec.ts`, importing `test`\/`expect` from `@playwright\/test`.\n6. **Run**: `npx playwright test --project=components`. Open `http:\/\/localhost:5173\/playwright\/gallery\/index.html` in a browser to eyeball all stories.\n\n## Conventions\n\n- Story id: path under `src\/` without the `.story.*` extension, plus the export name \u2014 `src\/components\/Button.story.tsx` export `Primary` \u2192 `components\/Button\/Primary`. Any unique suffix works too: `mount('Button\/Primary')`. A `.story.vue` single-file component is one story, addressable by its path alone (its `default` export). With gallery types (`references\/typing.md`) ids are prefixed with the package name: `acme-ui\/components\/Button\/Primary`.\n- One export per scenario. Prefer a new story export over parameterizing an existing one \u2014 stories are greppable, reviewable documentation of component states.\n\n## Testing patterns\n\nExamples are React; the Vue equivalents differ only in story syntax.\n\n### Callbacks and events\n\n**The story owns the state and provides the callbacks.** Where the component takes callbacks, create the state inside the story, wire the callbacks to it, and record the state into a hidden form next to the component. Tests perform operations and assert on the recorded values:\n\n```tsx\nexport const Stateful = () => {\n  const [expanded, setExpanded] = useState(false);\n  return <>\n    <Expandable expanded={expanded} setExpanded={setExpanded} title=\"Title\">Details<\/Expandable>\n    <form hidden><input data-testid=\"expanded\" readOnly value={String(expanded)} \/><\/form>\n  <\/>;\n};\n```\n\n```ts\ntest('click should expand', async ({ mount }) => {\n  const component = await mount('components\/Expandable\/Stateful');\n  await component.locator('.codicon-chevron-right').click();\n  await expect(component.getByTestId('expanded')).toHaveValue('true');\n});\n```\n\nThis keeps the whole scenario in the browser: no callback marshalling, the story doubles as documentation, and the recorded state is visible when eyeballing the gallery. Record each observed value in its own `data-testid` input (`String(...)` or `JSON.stringify(...)` for payloads) and assert with `toHaveValue()` \u2014 a web-first assertion that retries until the state lands. The negative direction works the same way: perform the operation, then assert the value did **not** change.\n\n### Per-test props\n\nWhen a scenario is genuinely parametric (e.g. a boundary-value sweep), pass props as the second argument to `mount`; the gallery hands them to the story as its props. Keep props to plain serializable data \u2014 callbacks belong inside the story.\n\n```tsx\nexport const WithTitle = ({ title = 'Default' }: { title?: string }) =>\n  <Button title={title} \/>;\n```\n\n```ts\nconst component = await mount('components\/Button\/WithTitle', { title: 'Hello' });\n```\n\nProps are type-checked in two optional ways, see `references\/typing.md`: pass the story type as a template argument (`mount<typeof WithTitle>('components\/Button\/WithTitle', { title: 'Hello' })`, no setup), or generate gallery types with a small Vite plugin so the id itself is typed (`mount('acme-ui\/components\/Button\/WithTitle', { title: 'Hello' })`, with autocomplete and rename safety). Vue stories must additionally declare the props at runtime \u2014 see the `Typed props` sections in `references\/react.md` \/ `references\/vue.md`.\n\n### Prop transitions with `update()`\n\nTo test how a component reacts to a prop change **without remounting** (state preserved), call `component.update(newProps)` \u2014 it re-renders the same story with new props on the existing root:\n\n```ts\nconst component = await mount('components\/Counter\/Default', { value: 1 });\nawait expect(component.getByTestId('value')).toHaveText('1');\nawait component.update({ value: 2 });\nawait expect(component.getByTestId('value')).toHaveText('2');\n```\n\nThis requires the gallery to reuse its root\/instance (`references\/gallery-spec.md`); state survives as long as the story stays the same.\n\n### Multiple states in one test\n\nEach `mount()` navigates fresh, so tests are fully isolated and mounting several stories in one test is cheap:\n\n```ts\nawait expect(await mount('Button\/Primary')).toHaveScreenshot('primary.png');\nawait expect(await mount('Button\/Disabled')).toHaveScreenshot('disabled.png');\n```\n\nFor visual comparison, screenshot the returned root locator (as above), not the page, to avoid asserting on browser chrome.\n\n### Network mocking\n\nUse `page.route()` as usual \u2014 register routes before `mount()`, since mounting navigates. `serviceWorkers: 'block'` (set in the config above) keeps the app's own service worker from serving cached responses that shadow the routes. Teams with MSW handler libraries can start the worker inside a story or decorator instead.\n\n### Debugging stories\n\nOpen your gallery URL (`baseURL`) in a browser and call `await window.mount({ story: 'components\/Button\/Primary' })` from the devtools console \u2014 that is exactly what the `mount` fixture does. An unknown story rejects `window.mount`, which surfaces as the test's `mount()` throwing with a real stack. To browse without the console, give your gallery an optional index page.\n\n## Decision points\n\n- **Monorepos \/ non-`src` layouts**: change the glob and the id derivation in your gallery (`references\/gallery-spec.md`) to match, and prefix ids with the package name (`references\/typing.md`).\n- **Global providers** (theme, i18n, store, router): create a shared `decorator` helper next to the gallery and wrap components in stories; see `references\/react.md` \/ `references\/vue.md`.\n## References\n\n- `references\/gallery-spec.md` \u2014 the gallery endpoint contract to implement (**start here**).\n- `references\/typing.md` \u2014 optional typing for `mount`: explicit story types vs generated gallery types, with the Vite plugin.\n- `references\/react.md` \u2014 React walkthrough: providers, StrictMode, CSS.\n- `references\/vue.md` \u2014 Vue walkthrough: `.story.ts` and `.story.vue` stories, plugins.\n- `references\/migration.md` \u2014 migrating off `@playwright\/experimental-ct-react` \/ `-vue`.\n","use_cases":["Testing React or Vue components in isolation","Migrating from @playwright\/experimental-ct-react or -vue","Creating a story gallery for component testing"],"limitations":[],"compatibility":[],"setup_tip":null,"sample_input":null,"sample_output":null,"source_url":"https:\/\/github.com\/microsoft\/playwright\/blob\/b4d016aadc5cbd2b898a284307975fe73e05483d\/packages\/playwright-core\/src\/tools\/skills\/playwright-component-testing\/SKILL.md","source_commit":"b4d016aadc5cbd2b898a284307975fe73e05483d","license":null,"version":null,"listing_approved_at":"2026-11-21","created_at":"2026-11-20T13:36:33.000000Z","updated_at":"2026-11-21T09:43:53.000000Z","seo_title":"Component Testing with Playwright","seo_description":"Test React or Vue components in isolation using Playwright's built-in mount fixture. The test runs against a story gallery page hosted by the app's own dev server. No\u989d\u5916\u7684\u6e2c","seo_keywords":["Playwright component testing","React component testing","Vue component testing","Story gallery testing","Isolated component testing"]}}