Test React/Vue Components in Isolation
Advanced18 min
Use Playwright Component Testing to mount and test individual React, Vue, or Svelte components in a real browser without running the full application.
Prerequisites
- -Playwright installed
- -React, Vue, or Svelte project
- -Vite or Webpack build setup
Steps
1
Install component testing dependencies
Add the Playwright component testing package for your framework.
$ npm install -D @playwright/experimental-ct-react
Replace 'react' with 'vue' or 'svelte' for other frameworks: @playwright/experimental-ct-vue, @playwright/experimental-ct-svelte.
2
Create the component test config
Set up a dedicated config for component tests.
$ cat > playwright-ct.config.ts << 'EOF'
import { defineConfig, devices } from '@playwright/experimental-ct-react';
export default defineConfig({
testDir: './tests/components',
use: {
ctPort: 3100,
ctTemplateDir: './playwright',
},
projects: [
{
name: 'chromium',
use: { ...devices['Desktop Chrome'] },
},
],
});
EOF
3
Write a component test
Mount a component and test its behavior in a real browser.
$ mkdir -p tests/components && cat > tests/components/Button.spec.tsx << 'EOF'
import { test, expect } from '@playwright/experimental-ct-react';
import { Button } from '../../src/components/Button';
test('renders with label', async ({ mount }) => {
const component = await mount(<Button label="Click me" />);
await expect(component).toContainText('Click me');
});
test('handles click events', async ({ mount }) => {
let clicked = false;
const component = await mount(
<Button label="Submit" onClick={() => { clicked = true; }} />
);
await component.click();
expect(clicked).toBe(true);
});
test('applies disabled state', async ({ mount }) => {
const component = await mount(<Button label="Disabled" disabled />);
await expect(component).toBeDisabled();
});
EOF
4
Run component tests
Execute the component tests in a real browser environment.
$ npx playwright test -c playwright-ct.config.ts
5
Test with props and slots
Test components with different prop combinations and children.
$ cat > tests/components/Card.spec.tsx << 'EOF'
import { test, expect } from '@playwright/experimental-ct-react';
import { Card } from '../../src/components/Card';
test('renders with children', async ({ mount }) => {
const component = await mount(
<Card title="Test Card">
<p>Card content goes here</p>
</Card>
);
await expect(component.getByText('Test Card')).toBeVisible();
await expect(component.getByText('Card content goes here')).toBeVisible();
});
test('matches screenshot', async ({ mount }) => {
const component = await mount(<Card title="Visual Test" />);
await expect(component).toHaveScreenshot();
});
EOF
Full Script
FAQ
Discussion
Loading comments...