It’s 2 AM. Your CI pipeline just failed. The end-to-end tests are timing out again — not because the feature is broken, but because three unrelated API calls are flaky. You’ve been here before. You stare at the screen, wondering if there’s a better way to catch UI bugs without spinning up an entire app.
That’s exactly when I found Playwright Component Testing. If you’re building production UI with React or Vue, this tool will change how you think about test coverage.
Quick Start: Up and Running in 5 Minutes
Playwright Component Testing lets you mount individual UI components in a real browser — Chrome, Firefox, Safari — without booting a full app server. Think of it as Storybook for testability: real browser rendering, driven by the Playwright API you already know from E2E tests.
Start by adding the package to an existing project:
# For React projects
npm init playwright@latest -- --ct
# If you're adding to an existing Playwright project
npx playwright install
When the init wizard runs, pick your framework. It generates a playwright/index.html and a config entry in playwright.config.ts:
// playwright.config.ts
import { defineConfig, devices } from '@playwright/test';
export default defineConfig({
testDir: './src',
use: { baseURL: 'http://localhost:3100' },
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});
Now write your first component test. Say you have a Badge component:
// Badge.spec.tsx (React)
import { test, expect } from '@playwright/experimental-ct-react';
import Badge from './Badge';
test('renders error state', async ({ mount }) => {
const component = await mount(<Badge status="error" label="Failed" />);
await expect(component).toHaveText('Failed');
await expect(component).toHaveCSS('background-color', 'rgb(220, 38, 38)');
});
Run it:
npx playwright test --project=chromium Badge.spec.tsx
That’s it. No server, no mocking the entire app, no waiting for routing to settle. The component mounts, Playwright checks it, done.
Deep Dive: What’s Actually Happening Under the Hood
Playwright Component Testing runs on Vite under the hood. Call mount() and Playwright spins up a Vite-served page, injects your component into a fixture container, and returns a Locator handle — the same type you use in full E2E tests.
This matters because your component tests get real browser rendering, not jsdom. CSS transitions, scroll behavior, focus traps — all of it works exactly as it would in production.
Handling Props, Slots, and Events
The mount() function accepts a props option (Vue) or JSX props (React), plus event callbacks. Here’s a Vue example with a custom dropdown:
// Dropdown.spec.ts (Vue)
import { test, expect } from '@playwright/experimental-ct-vue';
import Dropdown from './Dropdown.vue';
test('emits select event on item click', async ({ mount }) => {
let selectedValue = '';
const component = await mount(Dropdown, {
props: {
options: ['Alpha', 'Beta', 'Gamma'],
onSelect: (val: string) => { selectedValue = val; },
},
});
await component.getByRole('button').click();
await component.getByText('Beta').click();
expect(selectedValue).toBe('Beta');
});
Notice you’re not using a spy library. The event handler is plain JavaScript — no spy instances, no mock configuration, nothing to tear down afterward.
Mocking Fetch and External Dependencies
Components that fetch data need mocks. Playwright’s page.route() API works inside component tests too:
test('shows user data from API', async ({ page, mount }) => {
await page.route('**/api/users/1', async route => {
await route.fulfill({
json: { id: 1, name: 'Hieu Nguyen', role: 'admin' },
});
});
const component = await mount(<UserProfile userId={1} />);
await expect(component.getByText('Hieu Nguyen')).toBeVisible();
await expect(component.getByText('admin')).toBeVisible();
});
This beats the classic jest.mock() approach because you’re intercepting at the network layer — exactly what a real browser does. No module-level trickery.
Advanced Usage: Patterns That Scale
Testing Component State Transitions
One of the hardest things to test with snapshot testing or unit tests is stateful behavior — loading states, error recovery, empty vs. populated lists. Playwright handles this cleanly:
test('shows skeleton, then content, then handles refetch', async ({ page, mount }) => {
let resolveRequest: () => void;
const requestPending = new Promise<void>(res => { resolveRequest = res; });
await page.route('**/api/posts', async route => {
await requestPending;
await route.fulfill({ json: [{ id: 1, title: 'First Post' }] });
});
const component = await mount(<PostList />);
// Loading state
await expect(component.getByTestId('skeleton')).toBeVisible();
// Trigger data
resolveRequest!();
await expect(component.getByText('First Post')).toBeVisible();
await expect(component.getByTestId('skeleton')).not.toBeVisible();
});
Reusing Fixtures Across Tests
If multiple tests need the same setup — a theme provider, a router context, a Pinia store — define a custom fixture once:
// fixtures.ts
import { test as base } from '@playwright/experimental-ct-react';
import { MemoryRouter } from 'react-router-dom';
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
export const test = base.extend({
mount: async ({ mount }, use) => {
await use(async (component: JSX.Element) => {
const qc = new QueryClient();
return mount(
<QueryClientProvider client={qc}>
<MemoryRouter>{component}</MemoryRouter>
</QueryClientProvider>
);
});
},
});
Then import test from ./fixtures instead of from Playwright directly. Every component you mount now has routing and query context — no copy-pasting wrappers across files.
Visual Regression with Screenshots
Playwright’s toHaveScreenshot() works inside component tests. It catches visual regressions that code review and lint both miss — the button that shifted two pixels, the icon that stopped rendering after a CSS tweak:
test('Button visual regression — primary variant', async ({ mount }) => {
const component = await mount(<Button variant="primary">Submit</Button>);
await expect(component).toHaveScreenshot('button-primary.png');
});
On first run, Playwright saves the baseline. After that, any pixel diff fails the test. Keep these screenshots committed to Git so your team shares the same baseline.
Practical Tips from the Trenches
Keep Tests Narrow
Component tests should cover one behavior per test, not one file. If your Table component has sorting, filtering, and pagination, write three separate tests. Narrow tests are faster to debug when they fail at 2 AM.
Avoid Testing Implementation Details
Don’t assert on internal state variables or private methods. Assert on what the user sees: text, visibility, CSS classes, emitted events. This makes tests resilient to refactors — you can rewrite the internals without touching a single test.
Run Component Tests in CI Separately from E2E
Most component tests finish in 100–500ms. Keep them in a separate CI job that runs on every push. Reserve full E2E runs for merge requests or scheduled nightly builds. This cuts feedback loops from minutes to seconds.
# .github/workflows/test.yml
jobs:
component-tests:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- run: npm ci
- run: npx playwright install chromium
- run: npx playwright test --project=chromium src/
Use update-snapshots Carefully
When you intentionally change a component’s appearance, run:
npx playwright test --update-snapshots
Then commit the new screenshots. Never auto-update snapshots in CI — a rogue style change will silently overwrite your baseline and you won’t catch it until a customer files a bug with an attachment.
Debugging Failing Tests
Nothing speeds up debugging like Playwright’s UI mode. Pop it open and you get a live browser, a timeline of every action, and DOM snapshots at each step:
npx playwright test --ui
When a test is flaky, drop await page.pause() into the test body. The browser halts and gives you a DevTools console to poke around. Much better than reading stack traces at 3 AM.
When to Use Component Testing vs E2E
Component testing is not a replacement for end-to-end tests — it’s a complement. Use component tests for what a single component does in isolation: rendering, user interactions, visual states. Use E2E tests for flows that cross boundaries: auth, checkout, multi-page navigation.
Aim for 80% of your UI surface covered by component tests. Then write focused E2E tests for the paths that really matter — login, checkout, any flow touching payment or auth. That combination gives you fast feedback on most changes without sacrificing confidence where it counts.
Playwright Component Testing still ships under the @playwright/experimental-ct-* package name, but the API has been stable across versions and teams are running it in production. Microsoft continues to invest in it actively. If your React or Vue codebase has real UI complexity, the two-hour setup repays itself within the first sprint.

