Skip to content

Playwright is a framework for Web Testing and Automation. It allows testing Chromium, Firefox and WebKit with a single API.

feat(ct): type the mount fixture via story template argument (#41920)

Pavel Feldman4a0c4e4e7841
diff --git a/docs/src/test-api/class-fixtures.md b/docs/src/test-api/class-fixtures.md
index 0c08b19da3..96c4926982 100644
--- a/docs/src/test-api/class-fixtures.md
+++ b/docs/src/test-api/class-fixtures.md
@@ -69,6 +69,51 @@ test('example test', async ({ page, context }) => {
});
```
+## method: Fixtures.mount
+* since: v1.62
+- returns: <[Locator]>
+
+Mounts a component story and returns a [Locator] pointing to the root element the story was rendered into. Scope your queries from the returned locator: `component.getByRole('button')`, not `page.getByRole('button')`.
+
+A **story** is a small wrapper component that embeds the component under test in one specific scenario: hard-coded props, mock data, providers, recorded callbacks. Stories are rendered by a **gallery** page that you implement and serve at [`property: TestOptions.baseURL`]. The gallery exposes `window.mount(params)` and `window.unmount()` functions that render a story into its root element. Each call to [`method: Fixtures.mount`] navigates to [`property: TestOptions.baseURL`] and calls `window.mount()` with the story id and props, so tests are fully isolated from each other.
+
+**Usage**
+
+```js
+test('click should expand', async ({ mount }) => {
+ const component = await mount('components/Expandable/Stateful');
+ await component.getByRole('button').click();
+ await expect(component.getByTestId('expanded')).toHaveValue('true');
+});
+```
+
+Pass the story type as a template argument to type-check the props:
+
+```js
+import type { WithTitle } from './Button.story';
+
+test('renders the title', async ({ mount }) => {
+ const component = await mount<typeof WithTitle>('Button/WithTitle', { title: 'Hello' });
+ await expect(component).toContainText('Hello');
+});
+```
+
+The returned locator is augmented with two methods:
+* `update(props)` - re-renders the same story with new props without remounting, preserving component state;
+* `unmount()` - unmounts the story.
+
+### param: Fixtures.mount.storyId
+* since: v1.62
+- `storyId` <[string]>
+
+Identifier of the story to mount, as resolved by the gallery page. Conventionally, the story file path plus the exported story name, for example `'components/Button/Primary'`.
+
+### param: Fixtures.mount.props
+* since: v1.62
+- `props` ?<[Object]>
+
+Optional plain, serializable props passed to the story.
+
## property: Fixtures.page
* since: v1.10
- type: <[Page]>
diff --git a/docs/src/test-components-js.md b/docs/src/test-components-js.md
index 34fa303ab0..8d411a66ff 100644
--- a/docs/src/test-components-js.md
+++ b/docs/src/test-components-js.md
@@ -1,351 +1,158 @@
---
id: test-components
-title: "Components (experimental)"
+title: "Component testing"
---
-import LiteYouTube from '@site/src/components/LiteYouTube';
-
## Introduction
-Playwright Test can now test your components.
-
-<LiteYouTube
- id="y3YxX4sFJbM"
- title="Component testing"
-/>
-
-## Example
-
-Here is what a typical component test looks like:
+Playwright Test can test the components of your web application in isolation. A component test is a regular Playwright end-to-end test that runs against a small **story gallery** page served by your own dev server. There is no dedicated component-testing runtime, no bundler integration and no extra npm packages — the built-in [`method: Fixtures.mount`] fixture of `@playwright/test` drives it all.
```js
-test('event should work', async ({ mount }) => {
- let clicked = false;
-
- // Mount a component. Returns locator pointing to the component.
- const component = await mount(
- <Button title="Submit" onClick={() => { clicked = true }}></Button>
- );
+import { test, expect } from '@playwright/test';
- // As with any Playwright test, assert locator text.
- await expect(component).toContainText('Submit');
-
- // Perform locator click. This will trigger the event.
- await component.click();
-
- // Assert that respective events have been fired.
- expect(clicked).toBeTruthy();
+test('click should expand', async ({ mount }) => {
+ const component = await mount('components/Expandable/Stateful');
+ await component.getByRole('button').click();
+ await expect(component.getByTestId('expanded')).toHaveValue('true');
});
```
-## How to get started
-
-Adding Playwright Test to an existing project is easy. Below are the steps to enable Playwright Test for a React or Vue project.
-
-### Step 1: Install Playwright Test for components for your respective framework
-
-<Tabs
- groupId="js-package-manager"
- defaultValue="npm"
- values={[
- {label: 'npm', value: 'npm'},
- {label: 'yarn', value: 'yarn'},
- {label: 'pnpm', value: 'pnpm'},
- ]
-}>
-<TabItem value="npm">
-
-```bash
-npm init playwright@latest -- --ct
-```
-
-</TabItem>
+Tests run in Node.js while components run in a real browser: real clicks are triggered, real layout is executed, visual regression is possible. At the same time, tests get everything Playwright Test offers: parallelism, parametrization, retries and post-mortem tracing.
-<TabItem value="yarn">
+:::note
+This guide replaces the experimental `@playwright/experimental-ct-react` and `@playwright/experimental-ct-vue` packages. If you are using them today, see the [migration guide](#migration-from-the-experimental-packages) below.
+:::
-```bash
-yarn create playwright --ct
-```
+## Why a framework-agnostic approach
-</TabItem>
+The `@playwright/experimental-ct-*` packages let tests write JSX inline — `mount(<Button onClick={spy} />)`. To make that possible, Playwright had to control the entire pipeline: scan the tests for components, compile a bundle with its own copy of Vite and its own config, serve it from its own server, and marshal props and callbacks across the Node.js/browser boundary.
-<TabItem value="pnpm">
+That design kept the packages experimental forever:
-```bash
-pnpm create playwright --ct
-```
+- **It only worked when your setup matched ours.** Path aliases, plugins and CSS handling had to be mirrored into `ctViteConfig` by hand. Projects on webpack, Next.js or custom pipelines could not use their own build at all. Every framework needed its own package with its own runtime glue, and every new framework meant yet another package.
+- **The Node.js/browser boundary leaked.** JSX written in a test was compiled in Node.js and reassembled in the browser. Live objects could not cross, callbacks only half-worked through marshalling, and module mocks silently did not apply.
- </TabItem>
+The replacement inverts the control:
-</Tabs>
+- **You own the pipeline.** Components are built and served by your own dev server, with your plugins, your aliases and your CSS. Playwright does not compile or serve anything — it navigates to a page, like in any other test.
+- **It is framework-agnostic.** The only framework-specific piece is the gallery page — a small module that you own. React, Vue, Svelte, Solid or anything else: if your dev server can render it, Playwright can test it.
+- **It is stable.** Tests import `test` and `expect` from plain `@playwright/test`, and [`method: Fixtures.mount`] is a documented built-in fixture. There is no experimental package to depend on and no separate config dialect.
-This step creates several files in your workspace:
+## How it works
-```html title="playwright/index.html"
-<html lang="en">
- <body>
- <div id="root"></div>
- <script type="module" src="./index.ts"></script>
- </body>
-</html>
-```
+Three concepts make up the whole model:
-This file defines an html file that will be used to render components during testing.
-It must contain element with `id="root"`, that's where components are mounted. It must
-also link the script called `playwright/index.{js,ts,jsx,tsx}`.
+- 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.
+- The **gallery** is a single page, served by your dev server, that exposes `window.mount(params)` and `window.unmount()` functions rendering a story — resolved from your story files — into a `#root` element. It is framework-specific and yours to own.
+- The [`method: Fixtures.mount`] fixture navigates to the gallery ([`property: TestOptions.baseURL`]), calls `window.mount()` with the story id and props, and returns a [Locator] for the gallery root. Scope your queries from it: `component.getByRole('button').click()`.
-You can include stylesheets, apply theme and inject code into the page where
-component is mounted using this script. It can be either a `.js`, `.ts`, `.jsx` or `.tsx` file.
+Everything the component needs is set up *inside the story*, which runs in the browser. Everything the test asserts is observable *through the page*: DOM, URL, network.
-```js title="playwright/index.ts"
-// Apply theme here, add anything your component needs at runtime here.
-```
+## Getting started
-### Step 2. Create a test file `src/App.spec.{ts,tsx}`
+### Step 1: Point your coding agent at the skill
-<Tabs
- groupId="js-framework"
- defaultValue="react"
- values={[
- {label: 'React', value: 'react'},
- {label: 'Vue', value: 'vue'},
- ]
-}>
-<TabItem value="react">
+The gallery is application code — it belongs to you, not to Playwright. The fastest way to get one is to not write it yourself: Playwright ships this entire methodology as an agent skill. Install the skills and ask your coding agent (Claude Code, GitHub Copilot or similar) to do the setup:
-```js title="app.spec.tsx"
-import { test, expect } from '@playwright/experimental-ct-react';
-import App from './App';
-
-test('should work', async ({ mount }) => {
- const component = await mount(<App />);
- await expect(component).toContainText('Learn React');
-});
-```
-
-</TabItem>
-
-<TabItem value="vue">
-
-```js title="app.spec.ts"
-import { test, expect } from '@playwright/experimental-ct-vue';
-import App from './App.vue';
-
-test('should work', async ({ mount }) => {
- const component = await mount(App);
- await expect(component).toContainText('Learn Vue');
-});
-```
-
-```js title="app.spec.tsx"
-import { test, expect } from '@playwright/experimental-ct-vue';
-import App from './App.vue';
-
-test('should work', async ({ mount }) => {
- const component = await mount(<App />);
- await expect(component).toContainText('Learn Vue');
-});
-```
-If using TypeScript and Vue make sure to add a `vue.d.ts` file to your project:
-
-```js
-declare module '*.vue';
+```bash
+npx playwright init-skills
```
-</TabItem>
-
-</Tabs>
-
-### Step 3. Run the tests
-
-You can run tests using the [VS Code extension](./getting-started-vscode.md) or the command line.
-
-```sh
-npm run test-ct
+```txt
+Set up component testing using the playwright-component-testing skill.
```
-### Further reading: configure reporting, browsers, tracing
+The agent detects your framework and bundler, implements the gallery for your stack, adds a Playwright project to the config, and writes the first story and spec.
-Refer to [Playwright config](./test-configuration.md) for configuring your project.
+The contract the gallery fulfills is small and worth knowing, even if you never open the file:
-## Test stories
+- It is a single page under `playwright/gallery/`, served by **your own dev server** — Vite apps serve it with the dev server they already run; other setups run a small standalone Vite server next to the app.
+- It discovers your `*.story.*` files and exposes two functions: `window.mount({ story, props })` renders the story with the given id into a `#root` element, and `window.unmount()` tears it down. An unknown story or a render error rejects, which surfaces as the test's `mount()` call throwing.
+- It reuses the rendering root across calls, so `component.update(props)` reconciles instead of remounting and component state is preserved.
+- It imports your global CSS the same way the app entry does, and the body of `window.mount` is the natural place for app-wide setup — the equivalent of the old `beforeMount`/`afterMount` hooks.
-When Playwright Test is used to test web components, tests run in Node.js, while components run in the real browser. This brings together the best of both worlds: components run in the real browser environment, real clicks are triggered, real layout is executed, visual regression is possible. At the same time, test can use all the powers of Node.js as well as all the Playwright Test features. As a result, the same parallel, parametrized tests with the same post-mortem Tracing story are available during component testing.
+If you prefer to write the gallery by hand, the installed skill contains the full specification with worked React and Vue examples in `references/gallery-spec.md` — the whole page is a few dozen lines.
-This however, is introducing a number of limitations:
+### Step 2: Configure Playwright
-- You can't pass complex live objects to your component. Only plain JavaScript objects and built-in types like strings, numbers, dates etc. can be passed.
+Add a project to your `playwright.config.ts` and point `baseURL` at the gallery:
-```js
-test('this will work', async ({ mount }) => {
- const component = await mount(<ProcessViewer process={{ name: 'playwright' }}/>);
-});
+```js title="playwright.config.ts"
+import { defineConfig, devices } from '@playwright/test';
-test('this will not work', async ({ mount }) => {
- // `process` is a Node object, we can't pass it to the browser and expect it to work.
- const component = await mount(<ProcessViewer process={process}/>);
+export default defineConfig({
+ projects: [
+ {
+ name: 'components',
+ testDir: './tests/components',
+ use: {
+ ...devices['Desktop Chrome'],
+ baseURL: 'http://localhost:5173/playwright/gallery/index.html',
+ serviceWorkers: 'block',
+ reuseContext: true,
+ },
+ },
+ ],
+ webServer: {
+ command: 'npm run dev',
+ url: 'http://localhost:5173/playwright/gallery/index.html',
+ reuseExistingServer: !process.env.CI,
+ },
});
```
-- You can't pass data to your component synchronously in a callback:
+`mount` navigates to `baseURL`, so it must point at the gallery. `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 between tests in a worker — a large speedup for component suites, and the same optimization the experimental packages applied implicitly.
-```js
-test('this will not work', async ({ mount }) => {
- // () => 'red' callback lives in Node. If `ColorPicker` component in the browser calls the parameter function
- // `colorGetter` it won't get result synchronously. It'll be able to get it via await, but that is not how
- // components are typically built.
- const component = await mount(<ColorPicker colorGetter={() => 'red'}/>);
-});
-```
+### Step 3: Write a story
-Working around these and other limitations is quick and elegant: for every use case of the tested component, create a wrapper of this component designed specifically for test. Not only it will mitigate the limitations, but it will also offer powerful abstractions for testing where you would be able to define environment, theme and other aspects of your component rendering.
+Stories live next to the component they exercise. Each named export is one scenario:
-Let's say you'd like to test following component:
+```js title="src/components/Button.story.tsx"
+import { Button } from './Button';
-```js title="input-media.tsx"
-import React from 'react';
+export const Primary = () => <Button title='Submit' />;
-type InputMediaProps = {
- // Media is a complex browser object we can't send to Node while testing.
- onChange(media: Media): void;
-};
-
-export function InputMedia(props: InputMediaProps) {
- return <></> as any;
-}
+export const Disabled = () => <Button title='Submit' disabled />;
```
-Create a story file for your component:
+### Step 4: Write a test
-```js title="input-media.story.tsx"
-import React from 'react';
-import InputMedia from './import-media';
+```js title="tests/components/button.spec.ts"
+import { test, expect } from '@playwright/test';
-type InputMediaForTestProps = {
- onMediaChange(mediaName: string): void;
-};
-
-export function InputMediaForTest(props: InputMediaForTestProps) {
- // Instead of sending a complex `media` object to the test, send the media name.
- return <InputMedia onChange={media => props.onMediaChange(media.name)} />;
-}
-// Export more stories here.
-```
-
-Then test the component via testing the story:
-
-```js title="input-media.spec.tsx"
-import { test, expect } from '@playwright/experimental-ct-react';
-import { InputMediaForTest } from './input-media.story.tsx';
-
-test('changes the image', async ({ mount }) => {
- let mediaSelected: string | null = null;
-
- const component = await mount(
- <InputMediaForTest
- onMediaChange={mediaName => {
- mediaSelected = mediaName;
- }}
- />
- );
- await component
- .getByTestId('imageInput')
- .setInputFiles('src/assets/logo.png');
-
- await expect(component.getByAltText(/selected image/i)).toBeVisible();
- await expect.poll(() => mediaSelected).toBe('logo.png');
+test('renders primary button', async ({ mount }) => {
+ const component = await mount('components/Button/Primary');
+ await expect(component.getByRole('button')).toHaveText('Submit');
});
-```
-
-As a result, for every component you'll have a story file that exports all the stories that are actually tested.
-These stories live in the browser and "convert" complex object into the simple objects that can be accessed in the test.
-
-## Under the hood
-
-Here is how component testing works:
-
-- Once the tests are executed, Playwright creates a list of components that the tests need.
-- It then compiles a bundle that includes these components and serves it using a local static web server.
-- Upon the `mount` call within the test, Playwright navigates to the facade page `/playwright/index.html` of this bundle and tells it to render the component.
-- Events are marshalled back to the Node.js environment to allow verification.
-
-Playwright is using [Vite](https://vitejs.dev/) to create the components bundle and serve it.
-
-## Best practices and pitfalls
-
-Component tests are most reliable when they embrace the fact that the test runs in Node.js while the mounted component runs in the browser.
-
-### Prefer mounting inside each test
-
-Keep `mount()` close to the assertions that use it. Mounting in `beforeEach` makes it harder to see which component state belongs to which test and tends to hide accidental coupling between tests.
-```js
-test('renders the product name', async ({ mount }) => {
- const component = await mount(<ProductCard name="Playwright" />);
- await expect(component).toContainText('Playwright');
+test('disabled button is disabled', async ({ mount }) => {
+ const component = await mount('components/Button/Disabled');
+ await expect(component.getByRole('button')).toBeDisabled();
});
```
-### Module mocks do not cross the Node/browser boundary
-
-Module-level mocks such as `vi.mock()` or `jest.mock()` run in the test process. The component bundle runs in the browser, so those mocks do not automatically affect what the component imports at runtime. Prefer passing test-specific behavior through [`hooksConfig`](#hooks) and configuring it in `playwright/index.{js,ts,jsx,tsx}` with `beforeMount`.
-
-### Reset browser state when a component depends on globals
-
-Component testing may reuse the browser `context` and `page` between tests as a performance optimization. If a component depends on global browser state such as `localStorage`, cookies, singleton services, or router state, reset that state in your test setup or in [`beforeMount`](#hooks) so each test starts from a known baseline.
-
-## API reference
-
-### props
-
-Provide props to a component when mounted.
-
-<Tabs
- groupId="js-framework"
- defaultValue="react"
- values={[
- {label: 'React', value: 'react'},
- {label: 'Vue', value: 'vue'},
- ]
-}>
-
-<TabItem value="react">
-
-```js title="component.spec.tsx"
-import { test } from '@playwright/experimental-ct-react';
+### Step 5: Run
-test('props', async ({ mount }) => {
- const component = await mount(<Component msg="greetings" />);
-});
+```sh
+npx playwright test --project=components
```
-</TabItem>
-<TabItem value="vue">
-
-```js title="component.spec.ts"
-import { test } from '@playwright/experimental-ct-vue';
-
-test('props', async ({ mount }) => {
- const component = await mount(Component, { props: { msg: 'greetings' } });
-});
-```
+## Stories as a methodology
-```js title="component.spec.tsx"
-// Or alternatively, using the `jsx` style
-import { test } from '@playwright/experimental-ct-vue';
+Stories are not just a testing workaround — they are greppable, reviewable documentation of your component states, and the conventions keep them that way:
-test('props', async ({ mount }) => {
- const component = await mount(<Component msg="greetings" />);
-});
-```
+- **One export per scenario.** Prefer a new story export over parameterizing an existing one. `Button.story.tsx` exporting `Primary`, `Disabled`, `WithLongTitle` reads as a specification of the component.
+- **Stories live next to the component.** `src/components/Button.story.tsx` documents `src/components/Button.tsx`. Renames and refactors touch both together.
+- **Story ids are derived from the file path**: path under `src/` without the `.story.*` extension, plus the export name — `components/Button/Primary`. Any unique suffix works too: `mount('Button/Primary')`.
+- **The story owns everything the component needs**: providers, mock data, state, callbacks. The test owns nothing but interactions and assertions.
-</TabItem>
+Because every story is a named, addressable page state, the gallery doubles as a living catalog: open the gallery URL in a browser and render any story to inspect it by eye.
-</Tabs>
+## Testing patterns
-### callbacks / events
+### Record state for assertions
-Provide callbacks/events to a component when mounted.
+Components take callbacks; tests want to assert they fired. Instead of marshalling callbacks between Node.js and the browser, **the story owns the state and provides the callbacks** — and records the observable outcome into a hidden form next to the component:
<Tabs
groupId="js-framework"
@@ -355,487 +162,192 @@ Provide callbacks/events to a component when mounted.
{label: 'Vue', value: 'vue'},
]
}>
-
<TabItem value="react">
-```js title="component.spec.tsx"
-import { test } from '@playwright/experimental-ct-react';
+```js title="src/components/Expandable.story.tsx"
+import { useState } from 'react';
+import { Expandable } from './Expandable';
-test('callback', async ({ mount }) => {
- const component = await mount(<Component onClick={() => {}} />);
-});
+export const Stateful = () => {
+ const [expanded, setExpanded] = useState(false);
+ return <>
+ <Expandable expanded={expanded} setExpanded={setExpanded} title='Title'>Details</Expandable>
+ <form hidden><input data-testid='expanded' readOnly value={String(expanded)} /></form>
+ </>;
+};
```
</TabItem>
<TabItem value="vue">
-```js title="component.spec.ts"
-import { test } from '@playwright/experimental-ct-vue';
+```js title="src/components/Expandable.story.ts"
+import { defineComponent, h, ref } from 'vue';
+import Expandable from './Expandable.vue';
-test('event', async ({ mount }) => {
- const component = await mount(Component, { on: { click() {} } });
-});
-```
-
-```js title="component.spec.tsx"
-// Or alternatively, using the `jsx` style
-import { test } from '@playwright/experimental-ct-vue';
-
-test('event', async ({ mount }) => {
- const component = await mount(<Component v-on:click={() => {}} />);
+export const Stateful = defineComponent(() => {
+ const expanded = ref(false);
+ return () => h('div', [
+ h(Expandable, {
+ 'expanded': expanded.value,
+ 'onUpdate:expanded': (value: boolean) => expanded.value = value,
+ 'title': 'Title',
+ }),
+ h('form', { hidden: true }, [
+ h('input', { 'data-testid': 'expanded', 'readonly': true, 'value': String(expanded.value) }),
+ ]),
+ ]);
});
```
</TabItem>
-
</Tabs>
-### children / slots
-
-Provide children/slots to a component when mounted.
-
-<Tabs
- groupId="js-framework"
- defaultValue="react"
- values={[
- {label: 'React', value: 'react'},
- {label: 'Vue', value: 'vue'},
- ]
-}>
-
-<TabItem value="react">
-
-```js title="component.spec.tsx"
-import { test } from '@playwright/experimental-ct-react';
-
-test('children', async ({ mount }) => {
- const component = await mount(<Component>Child</Component>);
-});
-```
-
-</TabItem>
-<TabItem value="vue">
-
-```js title="component.spec.ts"
-import { test } from '@playwright/experimental-ct-vue';
-
-test('slot', async ({ mount }) => {
- const component = await mount(Component, { slots: { default: 'Slot' } });
-});
-```
-
-```js title="component.spec.tsx"
-// Or alternatively, using the `jsx` style
-import { test } from '@playwright/experimental-ct-vue';
-
-test('children', async ({ mount }) => {
- const component = await mount(<Component>Child</Component>);
+```js title="tests/components/expandable.spec.ts"
+test('click should expand', async ({ mount }) => {
+ const component = await mount('components/Expandable/Stateful');
+ await component.getByRole('button').click();
+ await expect(component.getByTestId('expanded')).toHaveValue('true');
});
```
-</TabItem>
-
-</Tabs>
-
-### hooks
-
-You can use `beforeMount` and `afterMount` hooks to configure your app. This lets you set up things like your app router, fake server etc. giving you the flexibility you need. You can also pass custom configuration from the `mount` call from a test, which is accessible from the `hooksConfig` fixture. This includes any config that needs to be run before or after mounting the component. An example of configuring a router is provided below:
-
-<Tabs
- groupId="js-framework"
- defaultValue="react"
- values={[
- {label: 'React', value: 'react'},
- {label: 'Vue', value: 'vue'},
- ]
-}>
- <TabItem value="react">
-
- ```js title="playwright/index.tsx"
- import { beforeMount, afterMount } from '@playwright/experimental-ct-react/hooks';
- import { BrowserRouter } from 'react-router-dom';
-
- export type HooksConfig = {
- enableRouting?: boolean;
- }
-
- beforeMount<HooksConfig>(async ({ App, hooksConfig }) => {
- if (hooksConfig?.enableRouting)
- return <BrowserRouter><App /></BrowserRouter>;
- });
- ```
-
- ```js title="src/pages/ProductsPage.spec.tsx"
- import { test, expect } from '@playwright/experimental-ct-react';
- import type { HooksConfig } from '../playwright';
- import { ProductsPage } from './pages/ProductsPage';
-
- test('configure routing through hooks config', async ({ page, mount }) => {
- const component = await mount<HooksConfig>(<ProductsPage />, {
- hooksConfig: { enableRouting: true },
- });
- await expect(component.getByRole('link')).toHaveAttribute('href', '/products/42');
- });
- ```
-
- </TabItem>
-
- <TabItem value="vue">
-
- ```js title="playwright/index.ts"
- import { beforeMount, afterMount } from '@playwright/experimental-ct-vue/hooks';
- import { router } from '../src/router';
-
- export type HooksConfig = {
- enableRouting?: boolean;
- }
-
- beforeMount<HooksConfig>(async ({ app, hooksConfig }) => {
- if (hooksConfig?.enableRouting)
- app.use(router);
- });
- ```
-
- ```js title="src/pages/ProductsPage.spec.ts"
- import { test, expect } from '@playwright/experimental-ct-vue';
- import type { HooksConfig } from '../playwright';
- import ProductsPage from './pages/ProductsPage.vue';
-
- test('configure routing through hooks config', async ({ page, mount }) => {
- const component = await mount<HooksConfig>(ProductsPage, {
- hooksConfig: { enableRouting: true },
- });
- await expect(component.getByRole('link')).toHaveAttribute('href', '/products/42');
- });
- ```
-
- </TabItem>
-
-</Tabs>
-
-### unmount
-
-Unmount the mounted component from the DOM. This is useful for testing the component's behavior upon unmounting. Use cases include testing an "Are you sure you want to leave?" modal or ensuring proper cleanup of event handlers to prevent memory leaks.
-
-<Tabs
- groupId="js-framework"
- defaultValue="react"
- values={[
- {label: 'React', value: 'react'},
- {label: 'Vue', value: 'vue'},
- ]
-}>
-
-<TabItem value="react">
+This pattern is the heart of the methodology:
-```js title="component.spec.tsx"
-import { test } from '@playwright/experimental-ct-react';
+- The whole scenario runs in the browser — no callback marshalling, no Node.js/browser boundary to leak through.
+- `toHaveValue()` is a web-first assertion: it retries until the state lands, so there is nothing to await or poll manually.
+- Record each observed value in its own `data-testid` input — `String(...)` for scalars, `JSON.stringify(...)` for payloads. The negative direction works the same way: perform the operation, then assert the value did **not** change.
+- The recorded state is *visible when you open the story in the gallery*. Click the component by hand and watch the values change — the story doubles as a manual test page for the exact scenario the automated test covers. Keep the form `hidden` for a clean screenshot baseline, or drop the `hidden` attribute while developing to see the state live next to the component.
-test('unmount', async ({ mount }) => {
- const component = await mount(<Component/>);
- await component.unmount();
-});
-```
+### Per-test props
-</TabItem>
-<TabItem value="vue">
+When a scenario is genuinely parametric — a boundary-value sweep, a text matrix — pass plain serializable props as the second argument to `mount`. The gallery hands them to the story as its props:
-```js title="component.spec.ts"
-import { test } from '@playwright/experimental-ct-vue';
+```js title="src/components/Button.story.tsx"
+import { Button } from './Button';
-test('unmount', async ({ mount }) => {
- const component = await mount(Component);
- await component.unmount();
-});
+export const WithTitle = ({ title = 'Default' }: { title?: string }) =>
+ <Button title={title} />;
```
-```js title="component.spec.tsx"
-// Or alternatively, using the `jsx` style
-import { test } from '@playwright/experimental-ct-vue';
+```js title="tests/components/button.spec.ts"
+import type { WithTitle } from '../../src/components/Button.story';
-test('unmount', async ({ mount }) => {
- const component = await mount(<Component/>);
- await component.unmount();
-});
+const component = await mount<typeof WithTitle>('Button/WithTitle', { title: 'Hello' });
```
-</TabItem>
-</Tabs>
+`mount` is generic over the story: pass the story type as a template argument and the props (and `update()`) are type-checked against the story signature. Keep props to plain serializable data — callbacks belong inside the story.
-### update
+### Prop transitions with `update()`
-Update props, slots/children, and/or events/callbacks of a mounted component. These component inputs can change at any time and are typically provided by the parent component, but sometimes it is necessary to ensure that your components behave appropriately to new inputs.
+To test how a component reacts to a prop change **without remounting** — state preserved — call `component.update(newProps)`. It re-renders the same story with new props on the existing root:
-<Tabs
- groupId="js-framework"
- defaultValue="react"
- values={[
- {label: 'React', value: 'react'},
- {label: 'Vue', value: 'vue'},
- ]
-}>
-
-<TabItem value="react">
-
-```js title="component.spec.tsx"
-import { test } from '@playwright/experimental-ct-react';
-
-test('update', async ({ mount }) => {
- const component = await mount(<Component/>);
- await component.update(
- <Component msg="greetings" onClick={() => {}}>Child</Component>
- );
-});
+```js
+const component = await mount('components/Counter/Default', { value: 1 });
+await expect(component.getByTestId('value')).toHaveText('1');
+await component.update({ value: 2 });
+await expect(component.getByTestId('value')).toHaveText('2');
```
-</TabItem>
-<TabItem value="vue">
-
-```js title="component.spec.ts"
-import { test } from '@playwright/experimental-ct-vue';
+### Multiple states and visual comparison
-test('update', async ({ mount }) => {
- const component = await mount(Component);
- await component.update({
- props: { msg: 'greetings' },
- on: { click() {} },
- slots: { default: 'Child' }
- });
-});
-```
+Each `mount()` navigates fresh, so tests are fully isolated and mounting several stories in one test is cheap:
-```js title="component.spec.tsx"
-// Or alternatively, using the `jsx` style
-import { test } from '@playwright/experimental-ct-vue';
-
-test('update', async ({ mount }) => {
- const component = await mount(<Component/>);
- await component.update(
- <Component msg="greetings" v-on:click={() => {}}>Child</Component>
- );
-});
+```js
+await expect(await mount('Button/Primary')).toHaveScreenshot('primary.png');
+await expect(await mount('Button/Disabled')).toHaveScreenshot('disabled.png');
```
-</TabItem>
-
-</Tabs>
+Screenshot the returned root locator, not the page, to avoid asserting on browser chrome.
### Handling network requests
-Playwright provides an **experimental** `router` fixture to intercept and handle network requests. There are two ways to use the `router` fixture:
-* Call `router.route(url, handler)` that behaves similarly to [`method: Page.route`]. See the [network mocking guide](./mock.md) for more details.
-* Call `router.use(handlers)` and pass [MSW library](https://mswjs.io/) request handlers to it.
-
-Here is an example of reusing your existing MSW handlers in the test.
+Use [`method: Page.route`] as usual — register routes before `mount()`, since mounting navigates:
```js
-import { handlers } from '@src/mocks/handlers';
-
-test.beforeEach(async ({ router }) => {
- // install common handlers before each test
- await router.use(...handlers);
-});
-
-test('example test', async ({ mount }) => {
- // test as usual, your handlers are active
- // ...
+test('renders the error state', async ({ page, mount }) => {
+ await page.route('**/api/items', route => route.fulfill({ status: 500 }));
+ const component = await mount('components/ItemList/Default');
+ await expect(component.getByRole('alert')).toContainText('Something went wrong');
});
```
-You can also introduce a one-off handler for a specific test.
-
-```js
-import { http, HttpResponse } from 'msw';
+The `serviceWorkers: 'block'` option from the config keeps the app's own service worker from serving cached responses that would shadow the routes. Teams with [MSW](https://mswjs.io/) handler libraries can start the worker inside a story or decorator instead.
-test('example test', async ({ mount, router }) => {
- await router.use(http.get('/data', async ({ request }) => {
- return HttpResponse.json({ value: 'mocked' });
- }));
+### Debugging stories
- // test as usual, your handler is active
- // ...
-});
-```
+Open the gallery URL in a browser and call `await window.mount({ story: 'components/Button/Primary' })` from the DevTools console — that is exactly what the `mount` fixture does. An unknown story or a render error 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 listing all discovered stories.
-## Frequently asked questions
+## Migration from the experimental packages
-### What's the difference between `@playwright/test` and `@playwright/experimental-ct-{react,vue}`?
+The experimental packages compiled JSX in the test file and marshalled it into the browser. The gallery pattern moves the scenario into a story export that runs natively in the browser. Here is how the concepts map:
-```js
-test('…', async ({ mount, page, context }) => {
- // …
-});
-```
+| `@playwright/experimental-ct-*` | Story gallery |
+|---|---|
+| `mount(<Button onClick={spy} />)` | Stateful story: the story provides `onClick` and records the effect into a hidden input; the test asserts with `toHaveValue()` |
+| Plain data props from the test | Unchanged in spirit: `mount(id, props)` |
+| JSX children / slots from the test | One story export per composition (Vue: a `.story.vue` file for slot-heavy scenarios) |
+| `component.update(<Button count={2} />)` | `component.update({ count: 2 })` |
+| `component.unmount()` | `component.unmount()` |
+| `beforeMount` / `afterMount` hooks | The body of the gallery's `window.mount` (global), or story decorators (per-story) |
+| `hooksConfig` per-test variation | Props: `mount('App/Routing', { route: '/dashboard' })`, interpreted by the story |
+| `router` fixture / MSW handlers in Node.js | [`method: Page.route`] in the test, or MSW `setupWorker` inside a story |
+| `playwright/index.html` (styles, theme) | The gallery's `index.html` and entry module imports |
+| `ctViteConfig`, `ctPort`, `ctTemplateDir` | Gone — the gallery runs through your own dev server; the port lives in `webServer` and `baseURL` |
+| `defineConfig` from the ct package | Plain `defineConfig` from `@playwright/test` |
-`@playwright/experimental-ct-{react,vue}` wrap `@playwright/test` to provide an additional built-in component-testing specific fixture called `mount`:
+A typical spec migrates like this:
-<Tabs
- groupId="js-framework"
- defaultValue="react"
- values={[
- {label: 'React', value: 'react'},
- {label: 'Vue', value: 'vue'},
- ]
-}>
-<TabItem value="react">
-
-```js
+```js title="Before: button.spec.tsx"
import { test, expect } from '@playwright/experimental-ct-react';
-import HelloWorld from './HelloWorld';
-
-test.use({ viewport: { width: 500, height: 500 } });
-
-test('should work', async ({ mount }) => {
- const component = await mount(<HelloWorld msg="greetings" />);
- await expect(component).toContainText('Greetings');
-});
-```
-
-</TabItem>
-
-<TabItem value="vue">
+import Button from '../src/components/Button';
-```js
-import { test, expect } from '@playwright/experimental-ct-vue';
-import HelloWorld from './HelloWorld.vue';
-
-test.use({ viewport: { width: 500, height: 500 } });
-
-test('should work', async ({ mount }) => {
- const component = await mount(HelloWorld, {
- props: {
- msg: 'Greetings',
- },
- });
- await expect(component).toContainText('Greetings');
+test('counts clicks', async ({ mount }) => {
+ let clicks = 0;
+ const component = await mount(<Button title='Submit' onClick={() => ++clicks} />);
+ await component.getByRole('button').click();
+ expect(clicks).toBe(1);
});
```
-</TabItem>
-
-</Tabs>
-
-Additionally, it adds some config options you can use in your `playwright-ct.config.{ts,js}`.
-
-Finally, under the hood, each test re-uses the `context` and `page` fixture as a speed optimization for Component Testing.
-It resets them in between each test so it should be functionally equivalent to `@playwright/test`'s guarantee that you get a new, isolated `context` and `page` fixture per-test.
+```js title="After: src/components/Button.story.tsx"
+import { useState } from 'react';
+import { Button } from './Button';
-### I have a project that already uses Vite. Can I reuse the config?
-
-At this point, Playwright is bundler-agnostic, so it is not reusing your existing Vite config. Your config might have a lot of things we won't be able to reuse. So for now, you would copy your path mappings and other high level settings into the `ctViteConfig` property of Playwright config.
-
-```js
-import { defineConfig } from '@playwright/experimental-ct-react';
-
-export default defineConfig({
- use: {
- ctViteConfig: {
- // ...
- },
- },
-});
+export const CountsClicks = () => {
+ const [clicks, setClicks] = useState(0);
+ return <>
+ <Button title='Submit' onClick={() => setClicks(count => count + 1)} />
+ <form hidden><input data-testid='click-count' readOnly value={String(clicks)} /></form>
+ </>;
+};
```
-You can specify plugins via Vite config for testing settings. Note that once you start specifying plugins, you are responsible for specifying the framework plugin as well, `vue()` in this case:
+```js title="After: tests/components/button.spec.ts"
+import { test, expect } from '@playwright/test';
-```js
-import { defineConfig, devices } from '@playwright/experimental-ct-vue';
-
-import { resolve } from 'path';
-import vue from '@vitejs/plugin-vue';
-import AutoImport from 'unplugin-auto-import/vite';
-import Components from 'unplugin-vue-components/vite';
-
-export default defineConfig({
- testDir: './tests/component',
- use: {
- trace: 'on-first-retry',
- ctViteConfig: {
- plugins: [
- vue(),
- AutoImport({
- imports: [
- 'vue',
- 'vue-router',
- '@vueuse/head',
- 'pinia',
- {
- '@/store': ['useStore'],
- },
- ],
- dts: 'src/auto-imports.d.ts',
- eslintrc: {
- enabled: true,
- },
- }),
- Components({
- dirs: ['src/components'],
- extensions: ['vue'],
- }),
- ],
- resolve: {
- alias: {
- '@': resolve(__dirname, './src'),
- },
- },
- },
- },
+test('counts clicks', async ({ mount }) => {
+ const component = await mount('components/Button/CountsClicks');
+ await component.getByRole('button').click();
+ await expect(component.getByTestId('click-count')).toHaveValue('1');
});
```
-### How do I use CSS imports?
-
-If you have a component that imports CSS, Vite will handle it automatically. You can also use CSS pre-processors such as Sass, Less, or Stylus, and Vite will handle them as well without any additional configuration. However, corresponding CSS pre-processor needs to be installed.
-
-Vite has a hard requirement that all CSS Modules are named `*.module.[css extension]`. If you have a custom build config for your project normally and have imports of the form `import styles from 'styles.css'` you must rename your files to properly indicate they are to be treated as modules. You could also write a Vite plugin to handle this for you.
+Migrate incrementally: set up the gallery and the `components` project while the old CT project keeps running, port spec by spec, then drop the `@playwright/experimental-ct-*` dependency along with `playwright/index.html`, `playwright/index.ts` and `playwright/.cache`.
-Check [Vite documentation](https://vite.dev/guide/features#css) for more details.
+Things to watch for:
-### How can I test components that uses Pinia?
+- **Story ids are strings.** Renaming or moving a story breaks specs at runtime, not compile time. Using `mount<typeof Story>` at least ties the props to the story at compile time.
+- **Per-test JSX is gone.** A test that built a different JSX tree per test becomes one story export per composition — which is the point: every composition worth testing is worth naming and reviewing.
-Pinia needs to be initialized in `playwright/index.{js,ts,jsx,tsx}`. If you do this inside a `beforeMount` hook, the `initialState` can be overwritten on a per-test basis:
+## Frequently asked questions
-```js title="playwright/index.ts"
-import { beforeMount, afterMount } from '@playwright/experimental-ct-vue/hooks';
-import { createTestingPinia } from '@pinia/testing';
-import type { StoreState } from 'pinia';
-import type { useStore } from '../src/store';
+### How do I access the component's methods or its instance?
-export type HooksConfig = {
- store?: StoreState<ReturnType<typeof useStore>>;
-}
+Accessing a component's internal methods or its instance within test code is neither recommended nor supported. Instead, focus on observing and interacting with the component from a user's perspective — click it, look at the page, and record internal effects into the DOM through the story. Tests become less fragile and more valuable when they avoid implementation details. If a test fails when run from a user's perspective, it likely means the automated test has uncovered a genuine bug.
-beforeMount<HooksConfig>(async ({ hooksConfig }) => {
- createTestingPinia({
- initialState: hooksConfig?.store,
- /**
- * Use http intercepting to mock api calls instead:
- * https://playwright.dev/docs/mock#mock-api-requests
- */
- stubActions: false,
- createSpy(args) {
- console.log('spy', args)
- return () => console.log('spy-returns')
- },
- });
-});
-```
+### Can I keep using my bundler plugins, aliases and CSS setup?
-```js title="src/pinia.spec.ts"
-import { test, expect } from '@playwright/experimental-ct-vue';
-import type { HooksConfig } from '../playwright';
-import Store from './Store.vue';
-
-test('override initialState ', async ({ mount }) => {
- const component = await mount<HooksConfig>(Store, {
- hooksConfig: {
- store: { name: 'override initialState' }
- }
- });
- await expect(component).toContainText('override initialState');
-});
-```
+Yes — that is the core of the design. The gallery is served by your own dev server, so whatever your app can render, your stories can render. There is no second bundler config to keep in sync.
-### How do I access the component's methods or its instance?
+### What about frameworks other than React and Vue?
-Accessing a component's internal methods or its instance within test code is neither recommended nor supported. Instead, focus on observing and interacting with the component from a user's perspective, typically by clicking or verifying if something is visible on the page. Tests become less fragile and more valuable when they avoid interacting with internal implementation details, such as the component instance or its methods. Keep in mind that if a test fails when run from a user’s perspective, it likely means the automated test has uncovered a genuine bug in your code.
+Ask your coding agent to implement the gallery contract for your framework: resolve a story id to a component, render it into `#root`, reuse the root across calls so `update()` preserves state. The `mount` fixture does not know or care which framework is on the other side.
diff --git a/packages/html-reporter/src/chip.spec.ts b/packages/html-reporter/src/chip.spec.ts
index 770ce94722..291654cefa 100644
--- a/packages/html-reporter/src/chip.spec.ts
+++ b/packages/html-reporter/src/chip.spec.ts
@@ -16,10 +16,12 @@
import { expect, test } from '@playwright/test';
+import type { Auto, AutoCollapsed, Stateful, WithBody } from './chip.story';
+
test.use({ viewport: { width: 500, height: 500 } });
test('expand collapse', async ({ mount }) => {
- const component = await mount('chip/Auto');
+ const component = await mount<typeof Auto>('chip/Auto');
await expect(component.getByText('Chip body')).toBeVisible();
await component.getByText('Title').click();
await expect(component.getByText('Chip body')).not.toBeVisible();
@@ -29,13 +31,13 @@ test('expand collapse', async ({ mount }) => {
test('render long title', async ({ mount }) => {
const title = 'Extremely long title. '.repeat(10);
- const component = await mount('chip/Auto', { header: title });
+ const component = await mount<typeof Auto>('chip/Auto', { header: title });
await expect(component).toContainText('Extremely long title.');
await expect(component.getByText('Extremely long title.')).toHaveAttribute('title', title);
});
test('setExpanded is called', async ({ mount }) => {
- const component = await mount('chip/Stateful');
+ const component = await mount<typeof Stateful>('chip/Stateful');
await component.getByText('Title').click();
await expect(component.getByTestId('expanded')).toHaveValue('true');
await component.getByText('Title').click();
@@ -43,13 +45,13 @@ test('setExpanded is called', async ({ mount }) => {
});
test('body render prop is rendered', async ({ mount }) => {
- const component = await mount('chip/WithBody');
+ const component = await mount<typeof WithBody>('chip/WithBody');
await expect(component.getByText('Body from render prop')).toBeVisible();
await expect(component.getByText('Chip children')).toBeVisible();
});
test('setExpanded should work', async ({ mount }) => {
- const component = await mount('chip/AutoCollapsed');
+ const component = await mount<typeof AutoCollapsed>('chip/AutoCollapsed');
await component.getByText('Title').click();
await expect(component).toMatchAriaSnapshot(`
- button "Title" [expanded]
diff --git a/packages/html-reporter/src/headerView.spec.ts b/packages/html-reporter/src/headerView.spec.ts
index 67262ab994..b63213b1e8 100644
--- a/packages/html-reporter/src/headerView.spec.ts
+++ b/packages/html-reporter/src/headerView.spec.ts
@@ -16,10 +16,12 @@
import { expect, test } from '@playwright/test';
+import type { Default } from './headerView.story';
+
test.use({ viewport: { width: 720, height: 200 } });
test('should render counters', async ({ mount }) => {
- const component = await mount('headerView/Default');
+ const component = await mount<typeof Default>('headerView/Default');
await expect(component.locator('a', { hasText: 'All' }).locator('.counter')).toHaveText('90');
await expect(component.locator('a', { hasText: 'Passed' }).locator('.counter')).toHaveText('42');
await expect(component.locator('a', { hasText: 'Failed' }).locator('.counter')).toHaveText('31');
@@ -36,7 +38,7 @@ test('should render counters', async ({ mount }) => {
});
test('should toggle filters', async ({ page, mount }) => {
- const component = await mount('headerView/Default');
+ const component = await mount<typeof Default>('headerView/Default');
const filterText = component.getByTestId('filter-text');
await component.locator('a', { hasText: 'All' }).click();
await expect(filterText).toHaveValue('');
diff --git a/packages/html-reporter/src/testCaseView.spec.ts b/packages/html-reporter/src/testCaseView.spec.ts
index c9656d7c1d..511c207b2b 100644
--- a/packages/html-reporter/src/testCaseView.spec.ts
+++ b/packages/html-reporter/src/testCaseView.spec.ts
@@ -16,10 +16,12 @@
import { expect, test } from '@playwright/test';
+import type { AnnotationLinks, AttachmentLinks, Default, PrevNext, TwoAttempts } from './testCaseView.story';
+
test.use({ viewport: { width: 800, height: 600 } });
test('should render test case', async ({ mount }) => {
- const component = await mount('testCaseView/Default');
+ const component = await mount<typeof Default>('testCaseView/Default');
await expect(component.getByText('Annotation text', { exact: false }).first()).toBeVisible();
await expect(component.getByText('Hidden annotation')).toBeHidden();
await component.getByText('Annotations').click();
@@ -35,7 +37,7 @@ test('should render test case', async ({ mount }) => {
test('should render copy buttons for annotations', async ({ mount, page, context }) => {
await context.grantPermissions(['clipboard-read', 'clipboard-write']);
- const component = await mount('testCaseView/Default');
+ const component = await mount<typeof Default>('testCaseView/Default');
await expect(component.getByText('Annotation text', { exact: false }).first()).toBeVisible();
await component.getByText('Annotation text', { exact: false }).first().hover();
await expect(component.locator('.test-case-annotation').getByLabel('Copy to clipboard').first()).toBeVisible();
@@ -46,7 +48,7 @@ test('should render copy buttons for annotations', async ({ mount, page, context
});
test('should correctly render links in annotations', async ({ mount }) => {
- const component = await mount('testCaseView/AnnotationLinks');
+ const component = await mount<typeof AnnotationLinks>('testCaseView/AnnotationLinks');
const firstLink = component.getByText('https://playwright.dev/docs/intro').first();
await expect(firstLink).toBeVisible();
@@ -66,7 +68,7 @@ test('should correctly render links in annotations', async ({ mount }) => {
});
test('should correctly render links in attachments', async ({ mount }) => {
- const component = await mount('testCaseView/AttachmentLinks');
+ const component = await mount<typeof AttachmentLinks>('testCaseView/AttachmentLinks');
await component.getByText('first attachment').click();
const body = component.getByText('The body with https://playwright.dev/docs/intro link');
await expect(body).toBeVisible();
@@ -79,7 +81,7 @@ test('should correctly render links in attachments', async ({ mount }) => {
});
test('should correctly render links in attachment name', async ({ mount }) => {
- const component = await mount('testCaseView/AttachmentLinks');
+ const component = await mount<typeof AttachmentLinks>('testCaseView/AttachmentLinks');
const link = component.getByText('attachment with inline link').locator('a');
await expect(link).toHaveAttribute('href', 'https://github.com/microsoft/playwright/issues/31284');
await expect(link).toHaveText('https://github.com/microsoft/playwright/issues/31284');
@@ -89,7 +91,7 @@ test('should correctly render links in attachment name', async ({ mount }) => {
});
test('should correctly render prev and next', async ({ mount }) => {
- const component = await mount('testCaseView/PrevNext');
+ const component = await mount<typeof PrevNext>('testCaseView/PrevNext');
await expect(component).toMatchAriaSnapshot(`
- text: group
- link "« previous"
@@ -99,7 +101,7 @@ test('should correctly render prev and next', async ({ mount }) => {
});
test('total duration is selected run duration', async ({ mount, page }) => {
- const component = await mount('testCaseView/TwoAttempts');
+ const component = await mount<typeof TwoAttempts>('testCaseView/TwoAttempts');
await expect(component).toMatchAriaSnapshot(`
- text: "My test test.spec.ts:42 200ms chromium"
- tablist:
diff --git a/packages/playwright-core/src/tools/skills/playwright-component-testing/SKILL.md b/packages/playwright-core/src/tools/skills/playwright-component-testing/SKILL.md
index a475aefbf2..3780d2c120 100644
--- a/packages/playwright-core/src/tools/skills/playwright-component-testing/SKILL.md
+++ b/packages/playwright-core/src/tools/skills/playwright-component-testing/SKILL.md
@@ -89,6 +89,16 @@ export const WithTitle = ({ title = 'Default' }: { title?: string }) =>
const component = await mount('components/Button/WithTitle', { title: 'Hello' });
```
+`mount` is generic over the story: pass the story type as a template argument to type-check the props (and `update()`):
+
+```ts
+import type { WithTitle } from './Button.story';
+
+const component = await mount<typeof WithTitle>('components/Button/WithTitle', { title: 'Hello' });
+```
+
+This works for React and Vue stories alike; Vue stories must additionally declare the props at runtime — see the `Typed props` sections in `references/react.md` / `references/vue.md`.
+
### Prop transitions with `update()`
To test how a component reacts to a prop change **without remounting** (state preserved), call `component.update(newProps)` — it re-renders the same story with new props on the existing root:
diff --git a/packages/playwright-core/src/tools/skills/playwright-component-testing/references/react.md b/packages/playwright-core/src/tools/skills/playwright-component-testing/references/react.md
index 1d142a5377..4b879478c6 100644
--- a/packages/playwright-core/src/tools/skills/playwright-component-testing/references/react.md
+++ b/packages/playwright-core/src/tools/skills/playwright-component-testing/references/react.md
@@ -40,6 +40,23 @@ export const LoggedIn = () => (
Do not build the decorator into the gallery — keeping it in story files makes the wrapping visible and lets stories opt out.
+## Typed props
+
+`mount` is generic over the story: pass the story type as a template argument to type-check per-test props (and `update()`). Props are inferred from the component signature; function and class components both work.
+
+```tsx
+// src/components/Button.story.tsx
+export const WithTitle = ({ title = 'Default' }: { title?: string }) =>
+ <Button title={title} />;
+```
+
+```ts
+// src/components/button.spec.ts
+import type { WithTitle } from './Button.story';
+
+const component = await mount<typeof WithTitle>('components/Button/WithTitle', { title: 'Hello' });
+```
+
## CSS
- Global stylesheets: import them in your gallery entry (`playwright/gallery/main.tsx`, e.g. `import '../../src/index.css'`), mirroring the app's own entry point.
diff --git a/packages/playwright-core/src/tools/skills/playwright-component-testing/references/vue.md b/packages/playwright-core/src/tools/skills/playwright-component-testing/references/vue.md
index 4914f0e9af..fd9ff6d678 100644
--- a/packages/playwright-core/src/tools/skills/playwright-component-testing/references/vue.md
+++ b/packages/playwright-core/src/tools/skills/playwright-component-testing/references/vue.md
@@ -47,6 +47,29 @@ export function withStore(story: Component) {
For plugins that must be installed on the app instance (`app.use(...)`), add them in your gallery right after `createApp(...)` — that is the equivalent of the app's own bootstrap.
+## Typed props
+
+A story that takes per-test props declares them twice: in the setup signature (for the type) and in the `props` option (so Vue delivers them as props rather than `attrs`):
+
+```ts
+// src/components/Button.story.ts
+export const WithTitle = defineComponent(
+ (props: { title?: string }) => () => h(Button, { title: props.title ?? 'Default' }),
+ { props: ['title'] },
+);
+```
+
+`mount` is generic over the story: pass the story type as a template argument to type-check the props (and `update()`):
+
+```ts
+// src/components/button.spec.ts
+import type { WithTitle } from './Button.story';
+
+const component = await mount<typeof WithTitle>('components/Button/WithTitle', { title: 'Hello' });
+```
+
+Options-API stories (`defineComponent({ props: { ... } })`) infer props the same way. For `.story.vue` SFC stories, prop types are only inferable when the setup generates SFC types (Volar/vue-tsc); otherwise pass the props type directly: `mount<{ title?: string }>('components/Button.primary', { title: 'Hello' })`.
+
## CSS
Import global stylesheets in your gallery entry (`playwright/gallery/main.ts`, e.g. `import '../../src/assets/main.css'`), mirroring the app's entry point.
diff --git a/packages/playwright/src/index.ts b/packages/playwright/src/index.ts
index 92fdc6c0f2..96de0ecf35 100644
--- a/packages/playwright/src/index.ts
+++ b/packages/playwright/src/index.ts
@@ -505,7 +505,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures, UtilityTestFixt
throw new Error('The gallery page does not define window.mount().');
await w.mount(p);
}, params, { exposeFunctions: true });
- await use(async (storyId: string, props?: Record<string, any>) => {
+ await use(async (storyId: string, props?: any) => {
if (!baseURL)
throw new Error('mount() requires `baseURL` to point at the component gallery. Set it in your Playwright config.');
// The gallery is a single page (served at baseURL) that exposes window.mount()/window.unmount().
@@ -515,7 +515,7 @@ const playwrightFixtures: Fixtures<TestFixtures, WorkerFixtures, UtilityTestFixt
return Object.assign(page.locator('#root'), {
// update() re-renders the same story with new props without navigating; if the gallery
// reuses its root/instance, the framework reconciles and component state is preserved.
- update: (newProps?: Record<string, any>) => callMount({ story: storyId, props: newProps }),
+ update: (newProps?: any) => callMount({ story: storyId, props: newProps }),
unmount: () => page.evaluate(async () => {
await (window as any).unmount?.();
}),
diff --git a/packages/playwright/types/test.d.ts b/packages/playwright/types/test.d.ts
index 0ed849a7ce..2e7180bde3 100644
--- a/packages/playwright/types/test.d.ts
+++ b/packages/playwright/types/test.d.ts
@@ -7774,6 +7774,12 @@ export interface PlaywrightWorkerArgs {
browser: Browser;
}
+type StoryProps<Story> =
+ Story extends (props: infer Props) => any ? Props :
+ Story extends new (...args: any[]) => { $props: infer Props } ? Props :
+ Story extends new (props: infer Props, ...args: any[]) => any ? Props :
+ Story;
+
/**
* Playwright Test is based on the concept of the [test fixtures](https://playwright.dev/docs/test-fixtures). Test fixtures are used to
* establish environment for each test, giving the test everything it needs and nothing else.
@@ -7865,10 +7871,48 @@ export interface PlaywrightTestArgs {
*
*/
request: APIRequestContext;
- // Experimental, undocumented: mount a story from the component gallery and return a locator
- // for the gallery root, augmented with update()/unmount(). Scope the queries:
- // component.getByRole(...). See the playwright-component-testing skill.
- mount: (storyId: string, props?: Record<string, any>) => Promise<Locator & { update(props?: Record<string, any>): Promise<void>, unmount(): Promise<void> }>;
+ /**
+ * Mounts a component story and returns a [Locator](https://playwright.dev/docs/api/class-locator) pointing to the
+ * root element the story was rendered into. Scope your queries from the returned locator:
+ * `component.getByRole('button')`, not `page.getByRole('button')`.
+ *
+ * A **story** is a small wrapper component that embeds the component under test in one specific scenario: hard-coded
+ * props, mock data, providers, recorded callbacks. Stories are rendered by a **gallery** page that you implement and
+ * serve at [testOptions.baseURL](https://playwright.dev/docs/api/class-testoptions#test-options-base-url). The
+ * gallery exposes `window.mount(params)` and `window.unmount()` functions that render a story into its root element.
+ * Each call to [fixtures.mount(storyId[, props])](https://playwright.dev/docs/api/class-fixtures#fixtures-mount)
+ * navigates to [testOptions.baseURL](https://playwright.dev/docs/api/class-testoptions#test-options-base-url) and
+ * calls `window.mount()` with the story id and props, so tests are fully isolated from each other.
+ *
+ * **Usage**
+ *
+ * ```js
+ * test('click should expand', async ({ mount }) => {
+ * const component = await mount('components/Expandable/Stateful');
+ * await component.getByRole('button').click();
+ * await expect(component.getByTestId('expanded')).toHaveValue('true');
+ * });
+ * ```
+ *
+ * Pass the story type as a template argument to type-check the props:
+ *
+ * ```js
+ * import type { WithTitle } from './Button.story';
+ *
+ * test('renders the title', async ({ mount }) => {
+ * const component = await mount<typeof WithTitle>('Button/WithTitle', { title: 'Hello' });
+ * await expect(component).toContainText('Hello');
+ * });
+ * ```
+ *
+ * The returned locator is augmented with two methods:
+ * - `update(props)` - re-renders the same story with new props without remounting, preserving component state;
+ * - `unmount()` - unmounts the story.
+ * @param storyId Identifier of the story to mount, as resolved by the gallery page. Conventionally, the story file path plus the
+ * exported story name, for example `'components/Button/Primary'`.
+ * @param props Optional plain, serializable props passed to the story.
+ */
+ mount: <Story = Record<string, any>>(storyId: string, props?: StoryProps<Story>) => Promise<Locator & { update(props?: StoryProps<Story>): Promise<void>, unmount(): Promise<void> }>;
}
type ExcludeProps<A, B> = {
diff --git a/packages/web/src/components/codeMirrorWrapper.spec.ts b/packages/web/src/components/codeMirrorWrapper.spec.ts
index eb4a6355fc..885104dd29 100644
--- a/packages/web/src/components/codeMirrorWrapper.spec.ts
+++ b/packages/web/src/components/codeMirrorWrapper.spec.ts
@@ -16,6 +16,8 @@
import { expect, test } from '@playwright/test';
+import type { Default, Editable } from './codeMirrorWrapper.story';
+
test.use({ viewport: { width: 500, height: 500 } });
const javascriptSnippet = `import { test, expect } from '@playwright/test';
@@ -68,27 +70,27 @@ class Program
`;
test('highlight JavaScript', async ({ mount }) => {
- const component = await mount('components/codeMirrorWrapper/Default', { text: javascriptSnippet, highlighter: 'javascript' });
+ const component = await mount<typeof Default>('components/codeMirrorWrapper/Default', { text: javascriptSnippet, highlighter: 'javascript' });
await expect(component.locator('text="async"').first()).toHaveClass('cm-keyword');
});
test('highlight Python', async ({ mount }) => {
- const component = await mount('components/codeMirrorWrapper/Default', { text: pythonSnippet, highlighter: 'python' });
+ const component = await mount<typeof Default>('components/codeMirrorWrapper/Default', { text: pythonSnippet, highlighter: 'python' });
await expect(component.locator('text="async"').first()).toHaveClass('cm-keyword');
});
test('highlight Java', async ({ mount }) => {
- const component = await mount('components/codeMirrorWrapper/Default', { text: javaSnippet, highlighter: 'java' });
+ const component = await mount<typeof Default>('components/codeMirrorWrapper/Default', { text: javaSnippet, highlighter: 'java' });
await expect(component.locator('text="public"').first()).toHaveClass('cm-keyword');
});
test('highlight C#', async ({ mount }) => {
- const component = await mount('components/codeMirrorWrapper/Default', { text: csharpSnippet, highlighter: 'csharp' });
+ const component = await mount<typeof Default>('components/codeMirrorWrapper/Default', { text: csharpSnippet, highlighter: 'csharp' });
await expect(component.locator('text="public"').first()).toHaveClass('cm-keyword');
});
test('should report changes via onChange', async ({ mount, page }) => {
- const component = await mount('components/codeMirrorWrapper/Editable');
+ const component = await mount<typeof Editable>('components/codeMirrorWrapper/Editable');
await component.locator('.CodeMirror').click();
await page.keyboard.type('!');
await expect(component.getByTestId('value')).toHaveValue(/!/);
@@ -96,7 +98,7 @@ test('should report changes via onChange', async ({ mount, page }) => {
});
test('should not report changes when read-only', async ({ mount, page }) => {
- const component = await mount('components/codeMirrorWrapper/Editable', { readOnly: true });
+ const component = await mount<typeof Editable>('components/codeMirrorWrapper/Editable', { readOnly: true });
await component.locator('.CodeMirror').click();
await page.keyboard.type('!');
await expect(component.locator('.CodeMirror')).toContainText('initial');
@@ -104,7 +106,7 @@ test('should not report changes when read-only', async ({ mount, page }) => {
});
test('highlight lines', async ({ mount }) => {
- const component = await mount('components/codeMirrorWrapper/Default', {
+ const component = await mount<typeof Default>('components/codeMirrorWrapper/Default', {
text: javascriptSnippet,
highlighter: 'javascript',
highlight: [
diff --git a/packages/web/src/components/expandable.spec.ts b/packages/web/src/components/expandable.spec.ts
index 42ee28d872..660a97162f 100644
--- a/packages/web/src/components/expandable.spec.ts
+++ b/packages/web/src/components/expandable.spec.ts
@@ -16,37 +16,39 @@
import { expect, test } from '@playwright/test';
+import type { Collapsed, Expanded, Stateful, StatefulTitleClick } from './expandable.story';
+
test.use({ viewport: { width: 500, height: 500 } });
test('should render collapsed', async ({ mount }) => {
- const component = await mount('components/expandable/Collapsed');
+ const component = await mount<typeof Collapsed>('components/expandable/Collapsed');
await expect(component.locator('text=Title')).toBeVisible();
await expect(component.locator('text=Details')).toBeHidden();
await expect(component.locator('.codicon-chevron-right')).toBeVisible();
});
test('should render expanded', async ({ mount }) => {
- const component = await mount('components/expandable/Expanded');
+ const component = await mount<typeof Expanded>('components/expandable/Expanded');
await expect(component.locator('text=Title')).toBeVisible();
await expect(component.locator('text=Details')).toBeVisible();
await expect(component.locator('.codicon-chevron-down')).toBeVisible();
});
test('click should expand', async ({ mount }) => {
- const component = await mount('components/expandable/Stateful');
+ const component = await mount<typeof Stateful>('components/expandable/Stateful');
await component.locator('.codicon-chevron-right').click();
await expect(component.getByTestId('expanded')).toHaveValue('true');
await expect(component.locator('text=Details')).toBeVisible();
});
test('title click should expand when enabled', async ({ mount }) => {
- const component = await mount('components/expandable/StatefulTitleClick');
+ const component = await mount<typeof StatefulTitleClick>('components/expandable/StatefulTitleClick');
await component.getByText('Title').click();
await expect(component.getByTestId('expanded')).toHaveValue('true');
});
test('title click should not expand by default', async ({ mount }) => {
- const component = await mount('components/expandable/Stateful');
+ const component = await mount<typeof Stateful>('components/expandable/Stateful');
await component.getByText('Title').click();
await expect(component.locator('.codicon-chevron-right')).toBeVisible();
await expect(component.getByTestId('expanded')).toHaveValue('false');
diff --git a/packages/web/src/components/splitView.spec.ts b/packages/web/src/components/splitView.spec.ts
index ae3bd07472..696b97b2b2 100644
--- a/packages/web/src/components/splitView.spec.ts
+++ b/packages/web/src/components/splitView.spec.ts
@@ -16,10 +16,12 @@
import { expect, test } from '@playwright/test';
+import type { Default } from './splitView.story';
+
test.use({ viewport: { width: 500, height: 500 } });
test('should render', async ({ mount }) => {
- const component = await mount('components/splitView/Default');
+ const component = await mount<typeof Default>('components/splitView/Default');
const mainBox = await component.locator('#main').boundingBox();
const sidebarBox = await component.locator('#sidebar').boundingBox();
expect.soft(mainBox).toEqual({ x: 0, y: 0, width: 500, height: 400 });
@@ -27,7 +29,7 @@ test('should render', async ({ mount }) => {
});
test('should render sidebar first', async ({ mount }) => {
- const component = await mount('components/splitView/Default', { sidebarIsFirst: true });
+ const component = await mount<typeof Default>('components/splitView/Default', { sidebarIsFirst: true });
const mainBox = await component.locator('#main').boundingBox();
const sidebarBox = await component.locator('#sidebar').boundingBox();
expect.soft(mainBox).toEqual({ x: 0, y: 100, width: 500, height: 400 });
@@ -35,7 +37,7 @@ test('should render sidebar first', async ({ mount }) => {
});
test('should render horizontal split', async ({ mount }) => {
- const component = await mount('components/splitView/Default', { sidebarIsFirst: true, orientation: 'horizontal' });
+ const component = await mount<typeof Default>('components/splitView/Default', { sidebarIsFirst: true, orientation: 'horizontal' });
const mainBox = await component.locator('#main').boundingBox();
const sidebarBox = await component.locator('#sidebar').boundingBox();
expect.soft(mainBox).toEqual({ x: 100, y: 0, width: 400, height: 500 });
@@ -43,13 +45,13 @@ test('should render horizontal split', async ({ mount }) => {
});
test('should hide sidebar', async ({ mount }) => {
- const component = await mount('components/splitView/Default', { orientation: 'horizontal', sidebarHidden: true });
+ const component = await mount<typeof Default>('components/splitView/Default', { orientation: 'horizontal', sidebarHidden: true });
const mainBox = await component.locator('#main').boundingBox();
expect.soft(mainBox).toEqual({ x: 0, y: 0, width: 500, height: 500 });
});
test('drag resize', async ({ page, mount }) => {
- const component = await mount('components/splitView/Default');
+ const component = await mount<typeof Default>('components/splitView/Default');
await page.mouse.move(25, 400);
await page.mouse.down();
await page.mouse.move(25, 100);
diff --git a/packages/web/src/shared/imageDiffView.spec.ts b/packages/web/src/shared/imageDiffView.spec.ts
index a0afc75826..590b0f050b 100644
--- a/packages/web/src/shared/imageDiffView.spec.ts
+++ b/packages/web/src/shared/imageDiffView.spec.ts
@@ -16,10 +16,12 @@
import { expect, test } from '@playwright/test';
+import type { Default } from './imageDiffView.story';
+
test.use({ viewport: { width: 1000, height: 800 } });
test('should render links', async ({ mount }) => {
- const component = await mount('shared/imageDiffView/Default');
+ const component = await mount<typeof Default>('shared/imageDiffView/Default');
await expect(component.locator('a')).toHaveText([
'screenshot-diff.png',
'screenshot-actual.png',
@@ -28,7 +30,7 @@ test('should render links', async ({ mount }) => {
});
test('should show diff by default', async ({ mount }) => {
- const component = await mount('shared/imageDiffView/Default');
+ const component = await mount<typeof Default>('shared/imageDiffView/Default');
const image = component.locator('img');
const box = await image.boundingBox();
expect(box).toEqual(expect.objectContaining({ width: 48, height: 48 }));
diff --git a/utils/generate_types/index.js b/utils/generate_types/index.js
index f20b51e3b3..1dee2fe602 100644
--- a/utils/generate_types/index.js
+++ b/utils/generate_types/index.js
@@ -579,7 +579,6 @@ class TypesGenerator {
'Config',
'ExpectMatcherUtils',
'Matchers',
- 'PlaywrightTestArgs.mount',
'PlaywrightWorkerArgs.playwright',
'PlaywrightWorkerOptions.defaultBrowserType',
'PlaywrightWorkerOptions.reuseContext',
diff --git a/utils/generate_types/overrides-test.d.ts b/utils/generate_types/overrides-test.d.ts
index 337b202552..4a7273f223 100644
--- a/utils/generate_types/overrides-test.d.ts
+++ b/utils/generate_types/overrides-test.d.ts
@@ -305,14 +305,17 @@ export interface PlaywrightWorkerArgs {
browser: Browser;
}
+type StoryProps<Story> =
+ Story extends (props: infer Props) => any ? Props :
+ Story extends new (...args: any[]) => { $props: infer Props } ? Props :
+ Story extends new (props: infer Props, ...args: any[]) => any ? Props :
+ Story;
+
export interface PlaywrightTestArgs {
context: BrowserContext;
page: Page;
request: APIRequestContext;
- // Experimental, undocumented: mount a story from the component gallery and return a locator
- // for the gallery root, augmented with update()/unmount(). Scope the queries:
- // component.getByRole(...). See the playwright-component-testing skill.
- mount: (storyId: string, props?: Record<string, any>) => Promise<Locator & { update(props?: Record<string, any>): Promise<void>, unmount(): Promise<void> }>;
+ mount: <Story = Record<string, any>>(storyId: string, props?: StoryProps<Story>) => Promise<Locator & { update(props?: StoryProps<Story>): Promise<void>, unmount(): Promise<void> }>;
}
type ExcludeProps<A, B> = {