Component Testing with Playwright
๐งฉ Component Testing with Playwright
Playwright is commonly used for end-to-end (E2E) testing, but it also supports component testing — particularly useful when working with front-end frameworks like React, Vue, and Svelte.
Component testing allows you to test individual UI components in isolation, making it easier to catch bugs early during development.
✅ Prerequisites
Before you start, make sure you have:
Node.js installed
A front-end framework (e.g., React, Vue, or Svelte)
Playwright installed with component testing support
⚙️ Step 1: Install Playwright with Component Testing
Run the following command:
bash
Copy
Edit
npm create playwright@latest
During setup, choose:
Component testing
Your framework (React, Vue, etc.)
The browser(s) you want to use (Chromium, Firefox, WebKit)
Alternatively, install manually:
bash
Copy
Edit
npm install -D @playwright/experimental-ct-react
# Or use @playwright/experimental-ct-vue for Vue
๐งพ Step 2: Create a Component to Test
Here’s an example React component:
jsx
Copy
Edit
// Button.jsx
export function Button({ label }) {
return <button>{label}</button>;
}
๐งช Step 3: Write a Component Test
Create a test file (e.g., Button.spec.tsx):
tsx
Copy
Edit
import { test, expect } from '@playwright/experimental-ct-react';
import { Button } from './Button';
test('should render the button with correct label', async ({ mount }) => {
const component = await mount(<Button label="Click Me" />);
await expect(component).toContainText('Click Me');
});
This test mounts the Button component and verifies the text content.
๐ Step 4: Run the Tests
Start the component test runner:
bash
Copy
Edit
npx playwright test --project=react
Or open the UI mode for easier debugging:
bash
Copy
Edit
npx playwright test --ui
๐งฉ Component Testing vs E2E Testing
Feature Component Testing E2E Testing
Scope One component Full application
Speed Fast Slower
Debugging Easier (fewer variables) Harder (more moving parts)
Use case Unit/UI testing Full user journeys
✅ Advantages of Component Testing in Playwright
Fast feedback: Faster than full E2E tests
Isolated: Test just the component, not the whole app
Real browsers: Tests run in actual browsers, not just simulated environments
Learn Playwright Training Course in Hyderabad
Read More
Accessibility Testing with Playwright
Multi-Tab Testing in Playwright
Testing Shadow DOM Elements with Playwright
Writing Custom Reporters in Playwright
Visit Our IHUB Talent Training Institute in Hyderabad
Comments
Post a Comment