Playwright 26 ๐ญ Component Testing โ Experimental @playwright/experimental-ct-react
Playwright’s component testing is a middle ground between unit tests and end-to-end tests. It renders a single component inside a real browser, driven by a real Playwright test, so the assertions run against the actual DOM, the actual CSS, and the actual event system of the browser, while the test setup stays as small as a unit test.
The feature has been experimental since it landed, and the package names carry the flag in them: @playwright/experimental-ct-react, @playwright/experimental-ct-vue, @playwright/experimental-ct-svelte, and @playwright/experimental-ct-solid. The React variant is the one this chapter uses.
The mechanism is a Vite dev server that compiles the component, a playwright/index.html page that hosts a #root node, and a mount() helper that renders the component into that root inside the browser. The test sees the component through the ordinary Locator API, so every locator, every assertion, and every screenshot method works the same way it works in end-to-end tests.
This chapter walks through the scaffolding and the configuration file, the mount() and component fixtures, the setup file with beforeMount and afterMount, and the ctViteConfig that wires aliases and plugins into the dev server.
Key point: Playwright component testing renders one component inside a real browser using Vite, so assertions run against the real DOM and real CSS while the test stays as focused as a unit test; the package is experimental, the config is a playwright-ct.config.ts, and the entry point is await mount(<Component />).
Why component testing exists
The unit test gap. A React unit test with Testing Library runs in jsdom, a JavaScript re-implementation of the DOM. jsdom does not lay out elements, does not apply CSS, does not paint, and does not fire real browser events for every case. A test that passes in jsdom can still fail in the browser because the CSS is wrong, the layout is broken, or the event does not propagate the same way.
The E2E slowness. A Playwright end-to-end test launches the whole applicationโthe dev server, the API stubs, the router, the auth storeโfor every test. The cost per test is high, the setup is heavy, and a failure could come from any layer. The component test narrows the surface: one component, one assertion.
The framework-specific runner. Jest with Testing Library, Vitest with Testing Library, and each framework’s own ecosystem have their own configuration. Playwright’s component testing reuses the Playwright test runner, so test, expect, describe, hooks, retries, the trace viewer, and the reporter are the same as in the E2E tests. The mental model carries over.
The real browser. Playwright runs the component test in Chromium, Firefox, or WebKit. The layout, the fonts, the CSS cascade, the pointer events, and the focus behavior are the real ones. A component that renders differently in the browser will fail the component test, which is exactly the kind of failure the unit test misses.
The Vite compilation. The component test compiles the component through Vite, which means the imports, aliases, CSS modules, and TypeScript configuration are the project’s own. There is no second build pipeline to keep in sync with the application build.
The trade-off. The component test is slower than a unit testโit launches a browser, a dev server, and a page. It is faster than an E2E testโit does not boot the application. It does not replace either; it fills the gap between the pure logic test and the full journey test.
a. Scaffolding and the project layout
The scaffolder is the fastest path:
npm init playwright@latest -- --ct
It prompts for a framework (React, Vue, Svelte, Solid), creates a playwright/ folder, a playwright-ct.config.ts file, and a sample component test. For a manual setup:
npm i -D @playwright/experimental-ct-react
npx playwright install
The playwright/ folder contains two files:
playwright/index.htmlโ the HTML page that hosts the component. It has a<div id="root">and a<script type="module" src="./index.ts">tag.playwright/index.tsโ the setup file. It imports global CSS, fonts, and registers hooks.
The #root div is requiredโthat is where mount() renders.
<!-- playwright/index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Component Testing</title>
</head>
<body>
<!-- the mount point; mount() renders the component here -->
<div id="root"></div>
<!-- the setup file; imports styles and registers hooks -->
<script type="module" src="./index.ts"></script>
</body>
</html>
The setup file imports the global stylesheet so the component under test has the same look as in the application:
// playwright/index.ts
import '../src/index.css'; // global styles, same import as the app
The test files live next to the components. The default testMatch is **/*.spec.tsx, so the layout looks like this:
src/
Button.tsx
Button.spec.tsx
The scaffolded sample looks like this:
// src/App.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import App from './App';
test('renders the heading', async ({ mount }) => {
// mount() renders the component into the #root div
const component = await mount(<App />);
// component is a Locator pointing at the mounted root
await expect(component).toContainText('Hello');
});
Note that test and expect come from @playwright/experimental-ct-react, not from @playwright/test. The CT package exports an extended test that provides the mount and component fixtures.
b. The mount() helper and the component fixture
mount is the function that renders the component. It accepts a React element, waits for the render to settle, and returns a Locator that points at the mounted root. The component fixture is the same Locator, available on the test context.
test('renders with props', async ({ mount }) => {
// mount accepts a React element with props
const component = await mount(<Button label="Save" variant="primary" />);
// the returned locator addresses the mounted root
await expect(component).toHaveText('Save');
});
Props are passed as normal JSX. Callback props are real functions, so a click handler fires the same way it fires in the application:
test('fires the onClick', async ({ mount }) => {
let clicked = 0;
// pass a real function as a prop
const component = await mount(<Button onClick={() => clicked++} />);
await component.click();
expect(clicked).toBe(1);
});
component.update() re-renders the same root with new props. This is the way to test a prop change without remounting the component, which matters when the component holds internal state that should survive the update:
test('updates on prop change', async ({ mount }) => {
const component = await mount(<Counter count={0} />);
await expect(component).toHaveText('0');
// re-render the same root; internal state survives
await component.update(<Counter count={5} />);
await expect(component).toHaveText('5');
});
The component fixture is the same locator, useful when the test needs to share it across beforeEach hooks or helper functions:
test('uses the component fixture', async ({ mount, component }) => {
await mount(<Header title="Docs" />);
// the fixture points at the same root
await expect(component).toBeVisible();
});
Children, slots, and fragments are passed as normal JSX. A wrapper element is the way to test two components together:
test('renders a list of items', async ({ mount }) => {
const component = await mount(
<ul>
<Item label="one" />
<Item label="two" />
</ul>
);
await expect(component.getByRole('listitem')).toHaveCount(2);
});
c. The setup file, the hooks, and the hooksConfig
The playwright/index.ts file is the single setup entry. It imports CSS, registers beforeMount and afterMount, and any global mocks.
// playwright/index.ts
import '../src/index.css';
import '../src/fonts.css';
import { beforeMount, afterMount } from '@playwright/experimental-ct-react/hooks';
// runs before React renders the component
beforeMount(async ({ hooksConfig }) => {
// hooksConfig is the object passed to mount()
document.documentElement.dataset.theme = hooksConfig.theme ?? 'light';
});
// runs after React has mounted the component
afterMount(async ({ instance }) => {
// instance is the mounted React instance
console.log('mounted', instance);
});
The hooksConfig object is passed as the second argument to mount:
test('renders in the dark theme', async ({ mount }) => {
// the setup file reads hooksConfig.theme
const component = await mount(<Card />, {
hooksConfig: { theme: 'dark' },
});
await expect(component).toHaveAttribute('data-theme', 'dark');
});
The beforeMount / afterMount pair is the place for:
- Theme providers
- Global context providers
- Font loading
windowmocks (e.g.matchMedia)- Polyfills for the browser APIs the component uses
The afterMount receives the mounted React instance, which is most useful for assertions about the host page rather than the component itself.
The playwright/index.ts is compiled by Vite, so it can import anything the project imports, including TypeScript files and CSS modules.
d. The config file and ctViteConfig
The playwright-ct.config.ts is the configuration file. It is separate from the ordinary playwright.config.ts because the CT runner launches a Vite dev server, not the application.
// playwright-ct.config.ts
import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
testDir: './src', // where the *.spec.tsx files live
timeout: 10 * 1000, // per-test timeout
fullyParallel: true, // parallel tests across files
forbidOnly: !!process.env.CI,
retries: process.env.CI ? 2 : 0,
workers: process.env.CI ? 1 : undefined,
reporter: 'html',
use: {
trace: 'on-first-retry', // capture the trace on failure
ctPort: 3100, // the port the Vite dev server binds
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});
Two keys are specific to CT:
ctPortโ the port for the Vite dev server. The default is3100, and it only matters when two CT runs happen at once.ctViteConfigโ the inline Vite configuration. This is the hook for aliases, plugins, and CSS preprocessing.
// playwright-ct.config.ts (excerpt)
import path from 'node:path';
import { defineConfig } from '@playwright/experimental-ct-react';
export default defineConfig({
use: {
ctViteConfig: {
resolve: {
// mirror the application's alias so `@/components` resolves
alias: {
'@': path.resolve(__dirname, 'src'),
},
},
},
},
});
The ctTemplateDir option points at the folder with index.html and index.ts, and it defaults to playwright. The ctArgs option forwards CLI arguments to the dev server.
The config also supports test.use({ viewport }) inside a test file for a per-file viewport:
test.use({ viewport: { width: 400, height: 800 } });
test('renders on mobile', async ({ mount }) => {
const component = await mount(<Navbar />);
await expect(component).toBeVisible();
});
The projects array is the way to run the same component test in Chromium, Firefox, and WebKit. The devices helper is the same one the E2E config uses.
Complete Example Session
// ============================================
// PART 1: THE SCAFFOLDER
// ============================================
// $ npm init playwright@latest -- --ct
//
// Or manual install:
// $ npm i -D @playwright/experimental-ct-react
// $ npx playwright install
//
// The scaffolder creates:
// playwright/index.html
// playwright/index.ts
// playwright-ct.config.ts
// src/App.spec.tsx
// ============================================
// PART 2: THE INDEX HTML
// ============================================
// playwright/index.html
// <!DOCTYPE html>
// <html lang="en">
// <head>
// <meta charset="UTF-8" />
// <meta name="viewport" content="width=device-width, initial-scale=1.0" />
// <title>Component Testing</title>
// </head>
// <body>
// <div id="root"></div>
// <script type="module" src="./index.ts"></script>
// </body>
// </html>
// ============================================
// PART 3: THE SETUP FILE
// ============================================
// playwright/index.ts
import '../src/index.css';
import { beforeMount, afterMount } from '@playwright/experimental-ct-react/hooks';
beforeMount(async ({ hooksConfig }) => {
// apply the theme from hooksConfig before React renders
document.documentElement.dataset.theme = hooksConfig.theme ?? 'light';
});
afterMount(async ({ instance }) => {
// the mounted React instance
console.log('mounted', instance);
});
// ============================================
// PART 4: THE CONFIG
// ============================================
// playwright-ct.config.ts
import path from 'node:path';
import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
testDir: './src',
timeout: 10 * 1000,
fullyParallel: true,
retries: process.env.CI ? 2 : 0,
reporter: 'html',
use: {
trace: 'on-first-retry',
ctPort: 3100,
ctViteConfig: {
resolve: {
alias: { '@': path.resolve(__dirname, 'src') },
},
},
},
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
],
});
// ============================================
// PART 5: THE BASIC TEST
// ============================================
// src/App.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import App from './App';
test('renders the heading', async ({ mount }) => {
const component = await mount(<App />);
await expect(component).toContainText('Hello');
});
// ============================================
// PART 6: THE PROPS AND CALLBACKS
// ============================================
// src/Button.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import Button from './Button';
test('fires onClick', async ({ mount }) => {
let clicked = 0;
const component = await mount(<Button label="Save" onClick={() => clicked++} />);
await component.click();
await expect(component).toHaveText('Save');
expect(clicked).toBe(1);
});
// ============================================
// PART 7: THE COMPONENT UPDATE
// ============================================
// src/Counter.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import Counter from './Counter';
test('updates on prop change', async ({ mount }) => {
const component = await mount(<Counter count={0} />);
await expect(component).toHaveText('0');
await component.update(<Counter count={5} />);
await expect(component).toHaveText('5');
});
// ============================================
// PART 8: THE HOOKS CONFIG
// ============================================
// src/Card.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import Card from './Card';
test('renders in the dark theme', async ({ mount }) => {
const component = await mount(<Card />, {
hooksConfig: { theme: 'dark' },
});
await expect(component).toHaveAttribute('data-theme', 'dark');
});
// ============================================
// PART 9: THE SCREENSHOT TEST
// ============================================
// src/Button.spec.tsx
import { test, expect } from '@playwright/experimental-ct-react';
import Button from './Button';
test('matches the snapshot', async ({ mount }) => {
const component = await mount(<Button label="Save" />);
await expect(component).toHaveScreenshot();
});
// ============================================
// PART 10: THE PROJECTS
// ============================================
// playwright-ct.config.ts (excerpt)
import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
projects: [
{ name: 'chromium', use: { ...devices['Desktop Chrome'] } },
{ name: 'firefox', use: { ...devices['Desktop Firefox'] } },
{ name: 'webkit', use: { ...devices['Desktop Safari'] } },
],
});
The ten parts covered the scaffold, the host page, the setup file, the config, the basic test, the props and callbacks, the update, the hooksConfig, the screenshot, and the browser projects.
Quick Reference
Packages
| Package | Framework |
|---|---|
@playwright/experimental-ct-react | React |
@playwright/experimental-ct-vue | Vue |
@playwright/experimental-ct-svelte | Svelte |
@playwright/experimental-ct-solid | Solid |
Configuration keys
| Key | Purpose |
|---|---|
testDir | Where the *.spec.tsx files live |
ctPort | Vite dev server port |
ctViteConfig | Inline Vite config (aliases, plugins) |
ctTemplateDir | Folder with index.html and index.ts |
projects | Browsers to run the tests in |
Test API
| API | Effect |
|---|---|
test | Extended test from the CT package |
expect | The same Playwright expect |
mount(<C />) | Render the component, return a Locator |
component.update(<C />) | Re-render the same root |
hooksConfig | Object passed to beforeMount |
Setup hooks
| Hook | Signature |
|---|---|
beforeMount | ({ hooksConfig }) => void |
afterMount | ({ instance }) => void |
Best Practices
โ Do This:
// Mount one component per test
const component = await mount(<Button label="Save" />); // โ
// Use component.update for a prop change
await component.update(<Counter count={5} />); // โ
// Import global CSS in playwright/index.ts
import '../src/index.css'; // โ
// Use locators within the mounted component
await component.getByRole('button').click(); // โ
// Use toHaveScreenshot for visual regression
await expect(component).toHaveScreenshot(); // โ
// Use ctViteConfig for aliases
alias: { '@': path.resolve(__dirname, 'src') } // โ
// Use trace on first retry
trace: 'on-first-retry' // โ
โ Don’t Do This:
// Reach into the DOM directly
document.querySelector('.btn').click(); // โ
// Mount the whole application
await mount(<App />); // โ
// Skip the index.html #root div
// (mount needs the #root node) // โ
// Hardcode the port twice
ctPort: 3100, ctPort: 3100 // โ
// Use CT for a pure-logic test
test('adds', async ({ mount }) => { expect(add(1,2)).toBe(3); }); // โ
// Assume the package is stable
// (it is experimental, pin the version) // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
|---|---|---|
| Component renders empty | Missing #root div | Add <div id="root"> to index.html |
| Styles missing | CSS not imported | Import in playwright/index.ts |
| Alias fails | Vite config not mirrored | Add to ctViteConfig.resolve.alias |
| Slow startup | Vite compiles on first test | Reuse the dev server; ctPort |
| Screenshot flaky | Animations, fonts | Disable animations, await fonts |
| Hook doesn’t fire | Prop passed as fake | Pass a real function |
| Port conflict | Two CT runs | Change ctPort |
| API changed | Experimental package | Pin the Playwright version |
Real-World Examples
1. Basic render
test('renders', async ({ mount }) => {
const c = await mount(<App />);
await expect(c).toContainText('Hello');
});
2. Props
test('renders with props', async ({ mount }) => {
const c = await mount(<Button label="Save" />);
await expect(c).toHaveText('Save');
});
3. Callback
test('fires onClick', async ({ mount }) => {
let n = 0;
const c = await mount(<Button onClick={() => n++} />);
await c.click();
expect(n).toBe(1);
});
4. Children
test('renders children', async ({ mount }) => {
const c = await mount(<Card><p>Body</p></Card>);
await expect(c).toContainText('Body');
});
5. Update
test('updates on prop change', async ({ mount }) => {
const c = await mount(<Counter count={0} />);
await c.update(<Counter count={1} />);
await expect(c).toHaveText('1');
});
6. hooksConfig
test('dark theme', async ({ mount }) => {
const c = await mount(<Card />, { hooksConfig: { theme: 'dark' } });
await expect(c).toHaveAttribute('data-theme', 'dark');
});
7. Screenshot
test('screenshot', async ({ mount }) => {
const c = await mount(<Button label="Save" />);
await expect(c).toHaveScreenshot();
});
8. Aliased import
// ctViteConfig.resolve.alias mirrors '@' โ 'src'
import Button from '@/components/Button';
9. Multiple components
test('renders a list', async ({ mount }) => {
const c = await mount(<ul><Item label="a" /></ul>);
await expect(c.getByRole('listitem')).toHaveCount(1);
});
10. Form interaction
test('submits the form', async ({ mount }) => {
let submitted = false;
const c = await mount(<Form onSubmit={() => (submitted = true)} />);
await c.getByLabel('Email').fill('a@b.c');
await c.getByRole('button').click();
expect(submitted).toBe(true);
});
Visual
The Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Playwright test runner โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Browser (Chromium / Firefox / WebKit) โ โ
โ โ โ โ
โ โ playwright/index.html โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โ โ #root โ โ โ
โ โ โ mount(<Button />) renders here โ โ โ
โ โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โฒ โ
โ โ Vite dev server on ctPort โ
โ โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โ โ Component source, CSS, aliases, plugins โ โ
โ โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Mount Lifecycle
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ await mount(<Button />) โ
โ โ โ
โ โผ โ
โ beforeMount({ hooksConfig }) โ
โ โ โ
โ โผ โ
โ React renders into #root โ
โ โ โ
โ โผ โ
โ afterMount({ instance }) โ
โ โ โ
โ โผ โ
โ returns a Locator pointing at #root โ
โ โ โ
โ โผ โ
โ await component.update(<Button label="New" />) โ
โ โ โ
โ โผ โ
โ React re-renders into the same #root โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Where CT Sits
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ UNIT TEST COMPONENT TEST E2E TEST โ
โ jsdom real browser real app โ
โ Testing Library mount() page โ
โ fast medium slow โ
โ logic DOM + CSS journey โ
โ โ
โ โโโโโโโโโโโโโโบ โโโโโโโโโโโโโโบ โ
โ pure logic one component whole appโ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
The Config Keys
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ playwright-ct.config.ts โ
โ โ
โ testDir โ where *.spec.tsx live โ
โ ctPort โ Vite dev server port โ
โ ctViteConfig โ aliases, plugins, CSS preprocess โ
โ ctTemplateDirโ playwright/ folder โ
โ projects โ chromium / firefox / webkit โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
|---|---|
| Package | @playwright/experimental-ct-react |
| Status | Experimental |
| Bundler | Vite |
| Browsers | Chromium, Firefox, WebKit |
| Host page | playwright/index.html |
| Setup file | playwright/index.ts |
| Config | playwright-ct.config.ts |
| Render API | mount(<Component />) |
| Update API | component.update(<Component />) |
| Hooks | beforeMount, afterMount |
| Aliases | ctViteConfig.resolve.alias |
| Port | ctPort (default 3100) |
Key takeaways:
- Component testing renders one component in a real browser. The Vite dev server compiles the component,
playwright/index.htmlhosts the#rootnode, andmount()renders into it. The assertions run against the real DOM, CSS, and events, not jsdom. - The package name carries the experimental flag.
@playwright/experimental-ct-reactis the React variant, and the sibling packages cover Vue, Svelte, and Solid. Pin the Playwright version, because the API can change between releases. - The test API is the same as the E2E API.
test,expect, the Locator methods,toHaveScreenshot, the trace viewer, the reporter, and the retries all work the same way, so the mental model from the E2E tests carries over. - The setup file is the single setup hook.
playwright/index.tsimports global CSS and registersbeforeMountandafterMount. ThehooksConfigobject frommountflows intobeforeMount, and the React instance is available inafterMount. ctViteConfigmirrors the application’s build. Aliases, plugins, and CSS preprocessing are declared there, so the component test uses the same imports as the application. Without it, the aliased imports fail at compile time.component.update()re-renders the same root. This is the difference from a freshmount: the same root is reused, so the component’s internal state survives the prop change, which is what a test of a controlled/uncontrolled component needs.- The component test does not replace the unit test or the E2E test. It is the middle ground: heavier than jsdom but lighter than launching the application, and the right place for the DOM, CSS, and event behavior of a single component.
Remember: Playwright component testing is the real browser applied to one component. Vite compiles the source, mount() renders into the #root node of playwright/index.html, and the Playwright test runner drives the assertions through the ordinary Locator API. The setup file imports the global styles and registers the lifecycle hooks, the config declares the port and the Vite overrides, and component.update() re-renders the same root when the test needs a new prop. It is experimental, it is slower than jsdom, and it catches the layout, styling, and event bugs that the unit test cannot see.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!