Playwright 组件测试搭建
playwright-component-testing
使用 story 画廊通过 Playwright 搭建组件测试——基于内置的 mount fixture 生成 stories 和画廊开发页面,无需专门的组件测试运行时。在需要使用 Playwright 隔离测试 React 或 Vue 组件,或从 @playwright/experimental-ct-react / -vue 迁移时使用。
- License 许可
- Apache-2.0
- 最近更新
- 2026-11-14
- Stars
- ★ 10w
- Forks
- 6.9k
01 前言 Front Matter
- name
- playwright-component-testing
- description
- Set up component testing with Playwright using a story gallery — 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.
02 资源文件 64
- 参考文档html2pptx.md19.4 KB
- 许可证LICENSE.txt1.4 KB
- 参考文档ooxml.md10.1 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-contentTypes.xsd1.9 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-coreProperties.xsd2.5 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-digSig.xsd2.8 KB
- 参考文档ooxml/schemas/ecma/fouth-edition/opc-relationships.xsd1.3 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-chart.xsd73.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-chartDrawing.xsd6.8 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-diagram.xsd50.1 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-lockedCanvas.xsd624 B
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-main.xsd148.5 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-picture.xsd1.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-spreadsheetDrawing.xsd8.7 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/dml-wordprocessingDrawing.xsd14.4 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/pml.xsd81.7 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-additionalCharacteristics.xsd1.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-bibliography.xsd7.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-commonSimpleTypes.xsd6.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlDataProperties.xsd1.2 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-customXmlSchemaProperties.xsd880 B
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesCustom.xsd2.5 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesExtended.xsd3.4 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-documentPropertiesVariantTypes.xsd7.3 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-math.xsd22.8 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/shared-relationshipReference.xsd1.3 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/sml.xsd236.6 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-main.xsd25.5 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-officeDrawing.xsd24.7 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-presentationDrawing.xsd535 B
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-spreadsheetDrawing.xsd5.6 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/vml-wordprocessingDrawing.xsd3.9 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/wml.xsd167.4 KB
- 参考文档ooxml/schemas/ISO-IEC29500-4_2016/xml.xsd4.5 KB
- 参考文档ooxml/schemas/mce/mc.xsd3.1 KB
- 参考文档ooxml/schemas/microsoft/wml-2010.xsd25.9 KB
- 参考文档ooxml/schemas/microsoft/wml-2012.xsd3.7 KB
- 参考文档ooxml/schemas/microsoft/wml-2018.xsd901 B
- 参考文档ooxml/schemas/microsoft/wml-cex-2018.xsd1.7 KB
- 参考文档ooxml/schemas/microsoft/wml-cid-2016.xsd1002 B
- 参考文档ooxml/schemas/microsoft/wml-sdtdatahash-2020.xsd600 B
- 参考文档ooxml/schemas/microsoft/wml-symex-2015.xsd745 B
- 脚本ooxml/scripts/pack.py5.5 KB
- 脚本ooxml/scripts/unpack.py1.0 KB
- 脚本ooxml/scripts/validate.py1.9 KB
- 脚本ooxml/scripts/validation/__init__.py336 B
- 脚本ooxml/scripts/validation/base.py39.0 KB
- 脚本ooxml/scripts/validation/docx.py9.8 KB
- 脚本ooxml/scripts/validation/pptx.py12.0 KB
- 脚本ooxml/scripts/validation/redlining.py10.9 KB
- 参考文档references/gallery-spec.md6.1 KB
- 参考文档references/migration.md4.9 KB
- 参考文档references/react.md3.0 KB
- 参考文档references/typing.md6.7 KB
- 参考文档references/vue.md3.3 KB
- 脚本scripts/html2pptx.js36.9 KB
- 脚本scripts/inventory.py37.2 KB
- 脚本scripts/rearrange.py8.3 KB
- 脚本scripts/replace.py13.3 KB
- 脚本scripts/thumbnail.py15.1 KB
- 脚本templates/react/button.spec.ts830 B
- 其他templates/react/Button.story.tsx892 B
- 脚本templates/vue/button.spec.ts830 B
- 脚本templates/vue/Button.story.ts1.1 KB
03 SKILL.md 正文
Component Testing with Playwright
Test 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.
Concept
- 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 you implement to
references/gallery-spec.md: it exposeswindow.mount(params)/window.unmount()that render a story — resolved from your story files (e.g. withimport.meta.glob) — into#root. It is framework-specific and yours to own — there is no template to copy for it. - Tests are plain Playwright tests. The built-in
mount(storyId, props?)fixture (from@playwright/test) drives the gallery'swindow.mountand returns aLocatorfor the gallery root (#root). Scope the queries from there —component.getByRole('button').click(), notcomponent.click(). Nothing to scaffold for it.
Everything 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.
Setup workflow
-
Detect the framework and bundler. React vs Vue decides the framework notes and example story to follow. Then:
- App runs on Vite (has
vite.config.*): the gallery is served by the existing dev server at/playwright/gallery/index.html— Vite serves any.htmlfile under the project root, the app's plugins/aliases/CSS apply automatically, andvite buildignores it. No extra server needed. - Anything else (Next.js, webpack, no dev server): run a small standalone dev server (e.g. Vite) that serves the gallery page, and point
baseURLat it. Requiresviteand the framework plugin as devDependencies.
- App runs on Vite (has
-
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 inreferences/react.md/references/vue.md. Keep story discovery (import.meta.glob) and the framework mount here — 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. -
Configure Playwright — add to
playwright.config.ts: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', // or: npx vite --config playwright/vite.config.ts url: 'http://localhost:5173/playwright/gallery/index.html', // standalone server: http://localhost:3100/playwright/gallery/index.html reuseExistingServer: !process.env.CI, },Match the port to the dev server.
mountnavigates tobaseURL, so setbaseURLto the gallery's URL.serviceWorkers: 'block'keeps the app's own service worker from serving cached responses that would shadow yourpage.route()mocks.reuseContext: truereuses the browser context across tests in a worker (as the old component-testing runtime did) — a large speedup for component suites. If the config already has projects/webServer, merge instead of replacing. -
Write a first story next to an existing component, modeled on
templates/<react|vue>/Button.story.*. -
Write a first spec, modeled on
templates/react/button.spec.ts, importingtest/expectfrom@playwright/test. -
Run:
npx playwright test --project=components. Openhttp://localhost:5173/playwright/gallery/index.htmlin a browser to eyeball all stories.
Conventions
- Story id: path under
src/without the.story.*extension, plus the export name —src/components/Button.story.tsxexportPrimary→components/Button/Primary. Any unique suffix works too:mount('Button/Primary'). A.story.vuesingle-file component is one story, addressable by its path alone (itsdefaultexport). With gallery types (references/typing.md) ids are prefixed with the package name:acme-ui/components/Button/Primary. - One export per scenario. Prefer a new story export over parameterizing an existing one — stories are greppable, reviewable documentation of component states.
Testing patterns
Examples are React; the Vue equivalents differ only in story syntax.
Callbacks and events
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:
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>
</>;
};
test('click should expand', async ({ mount }) => {
const component = await mount('components/Expandable/Stateful');
await component.locator('.codicon-chevron-right').click();
await expect(component.getByTestId('expanded')).toHaveValue('true');
});
This 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() — 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.
Per-test props
When 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 — callbacks belong inside the story.
export const WithTitle = ({ title = 'Default' }: { title?: string }) =>
<Button title={title} />;
const component = await mount('components/Button/WithTitle', { title: 'Hello' });
Props 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 — 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:
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');
This requires the gallery to reuse its root/instance (references/gallery-spec.md); state survives as long as the story stays the same.
Multiple states in one test
Each mount() navigates fresh, so tests are fully isolated and mounting several stories in one test is cheap:
await expect(await mount('Button/Primary')).toHaveScreenshot('primary.png');
await expect(await mount('Button/Disabled')).toHaveScreenshot('disabled.png');
For visual comparison, screenshot the returned root locator (as above), not the page, to avoid asserting on browser chrome.
Network mocking
Use page.route() as usual — 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.
Debugging stories
Open your gallery URL (baseURL) 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 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.
Decision points
- Monorepos / non-
srclayouts: 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). - Global providers (theme, i18n, store, router): create a shared
decoratorhelper next to the gallery and wrap components in stories; seereferences/react.md/references/vue.md.
References
references/gallery-spec.md— the gallery endpoint contract to implement (start here).references/typing.md— optional typing formount: explicit story types vs generated gallery types, with the Vite plugin.references/react.md— React walkthrough: providers, StrictMode, CSS.references/vue.md— Vue walkthrough:.story.tsand.story.vuestories, plugins.references/migration.md— migrating off@playwright/experimental-ct-react/-vue.
04 同仓库更多 Skills
Playwright 追踪文件检查
playwright-trace
从命令行检查 Playwright trace 文件——列出操作、查看请求、控制台、错误、快照和屏幕截图。
Playwright 浏览器自动化
playwright-cli
自动化浏览器交互、测试网页并处理 Playwright 测试。
Playwright 测试结果查询
playwright-test-results
从聚合的 DuckDB 数据库中查询 Playwright CI 测试结果。无需在 GitHub 构建产物中逐一翻找,即可回答有关不稳定测试(flaky tests)、失败率、缓慢测试以及每次运行/SHA/PR 结果的问题。
Playwright 发布说明撰写
playwright-release-notes
为 Playwright 版本发布撰写发布说明——包括 docs/src/release-notes-js.md 中的 Node.js 说明,以及 Python、Java 和 .NET 的翻译版本,还有每种语言版本的 GitHub markdown 文档。当用户要求撰写、翻译或发布发布说明时使用。
Playwright CI 与发布运维
playwright-devops
Playwright 的 DevOps 工作流——CI 失败分析、工作流调试和发布操作。
Playwright 功能开发指南
playwright-dev
讲解如何开发 Playwright——添加 API、MCP 工具、CLI 命令以及供应商(vendor)依赖。