Vue 3 + Playwright Testing
Overview
To build reliable tests for Vue 3 applications, use Playwright for both end-to-end testing and experimental component testing. Playwright integrates seamlessly with Vue's reactivity system, Vue Router navigation, and Vite build pipeline. This skill provides Vue-specific guidance for writing maintainable tests while avoiding common pitfalls like timeout anti-patterns.
Current Versions: Playwright 1.48+, Vue 3.5+, Vite 6+
Standard Approach: Semantic locators, conditional waits, API mocking
Key Philosophy: Never use arbitrary timeouts to fix flaky tests
Decision Tree: What Type of Test?
Vue Test Request → What are you testing?
|
├─ End-to-end user flow (login, forms, navigation)?
│ ├─ Single page interaction? → Use Quick Start: E2E Test
│ └─ Multi-page workflow? → Load references/e2e-patterns.md
│
├─ Individual Vue component in isolation?
│ └─ Load references/component-testing.md
│
├─ Vue Router navigation or page transitions?
│ └─ Load references/vue-specific-patterns.md → Router section
│
├─ Reactive state changes or Pinia store?
│ └─ Load references/vue-specific-patterns.md → State Management
│
├─ Authentication flow?
│ └─ Load references/vue-specific-patterns.md → Authentication
│
├─ Test is failing intermittently/flaky?
│ └─ Load references/best-practices.md → Debugging Flaky Tests section
│
└─ Setting up Playwright in Vue project?
└─ Use Quick Start: Project Setup
Quick Start: Project Setup
Initialize Playwright in Vue Project
bash
1npm init playwright@latest -- --ct
This command:
- Installs
@playwright/test and @playwright/experimental-ct-vue
- Downloads browsers
- Creates
playwright.config.ts
- Sets up test structure
For Vue projects with Vite, ensure playwright.config.ts includes:
typescript
1import { defineConfig, devices } from '@playwright/test';
2import react from '@vitejs/plugin-react';
3import vue from '@vitejs/plugin-vue';
4
5export default defineConfig({
6 testDir: './tests',
7 fullyParallel: true,
8 forbidOnly: !!process.env.CI,
9 retries: process.env.CI ? 2 : 0,
10 workers: process.env.CI ? 1 : undefined,
11
12 use: {
13 baseURL: 'http://localhost:5173',
14 trace: 'on-first-retry',
15 screenshot: 'only-on-failure',
16 video: 'retain-on-failure',
17 },
18
19 webServer: {
20 command: 'npm run dev',
21 url: 'http://localhost:5173',
22 reuseExistingServer: !process.env.CI,
23 },
24
25 projects: [
26 { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
27 { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
28 { name: 'webkit', use: { ...devices['Desktop Safari'] } },
29 ],
30});
Quick Start: E2E Test
Basic E2E Test Example
typescript
1import { test, expect } from '@playwright/test';
2
3test.describe('Login Flow', () => {
4 test.beforeEach(async ({ page }) => {
5 await page.goto('/login');
6 });
7
8 test('user can login successfully', async ({ page }) => {
9 // Use semantic locators (getByLabel, getByRole)
10 await page.getByLabel('Email').fill('user@example.com');
11 await page.getByLabel('Password').fill('password123');
12
13 // Click submit button
14 await page.getByRole('button', { name: 'Sign in' }).click();
15
16 // Wait for URL change (condition-based, not timeout)
17 await expect(page).toHaveURL('/dashboard');
18
19 // Assert Vue app rendered correctly
20 await expect(page.getByRole('heading', { name: /Welcome/i })).toBeVisible();
21 });
22
23 test('invalid credentials show error', async ({ page }) => {
24 await page.getByLabel('Email').fill('bad@email.com');
25 await page.getByLabel('Password').fill('wrong');
26 await page.getByRole('button', { name: 'Sign in' }).click();
27
28 // Wait for error message to appear
29 await expect(page.getByRole('alert')).toContainText('Invalid credentials');
30 });
31});
Quick Start: Component Test
Testing Vue Component in Isolation
typescript
1import { test, expect } from '@playwright/experimental-ct-vue';
2import Button from './Button.vue';
3
4test('button emits click event', async ({ mount }) => {
5 const messages: string[] = [];
6
7 const component = await mount(Button, {
8 props: { label: 'Click me' },
9 on: {
10 click: () => messages.push('clicked')
11 }
12 });
13
14 await component.getByRole('button').click();
15 expect(messages).toEqual(['clicked']);
16});
Core Vue 3 + Playwright Principles
1. Never Use Arbitrary Timeouts to Fix Flaky Tests
❌ BAD: Masking the real issue
typescript
1// This is a code smell - something is wrong
2await page.waitForTimeout(3000);
3await page.click('button');
✅ GOOD: Wait for the specific condition
typescript
1// Wait for button to be enabled
2await page.locator('button:not([disabled])').waitFor();
3await page.getByRole('button').click();
4
5// Or use Playwright's auto-waiting
6await page.getByRole('button', { name: 'Submit' }).click();
Why? Arbitrary timeouts hide race conditions, selector problems, or network issues. When you see a flaky test, investigate the root cause:
- Is the selector wrong? Use dev tools to verify
- Is data loading? Wait for the API response
- Is Vue not mounted yet? Check the condition
- Is the element disabled? Wait for the disabled attribute to be removed
2. Use Semantic Locators for Stability
Priority order (most stable to least):
typescript
1// ✅ 1. User-facing text/roles (most stable)
2await page.getByRole('button', { name: 'Save' });
3await page.getByLabel('Email');
4await page.getByPlaceholder('Search...');
5await page.getByText('Welcome');
6
7// ✅ 2. Test IDs (when semantic locators insufficient)
8await page.getByTestId('product-card');
9
10// ❌ 3. CSS/XPath selectors (avoid - fragile)
11await page.locator('css=.dynamic-button');
3. Test Vue-Specific Behavior
Wait for Vue app to be ready before interactions:
typescript
1// Wait for Vue app to mount
2test('app loads correctly', async ({ page }) => {
3 await page.goto('/');
4
5 // Playwright auto-waits, but be explicit for Vue:
6 await page.waitForFunction(() => {
7 // Check Vue app is mounted
8 return !!(window as any).__VUE_DEVTOOLS_GLOBAL_HOOK__?.enabled;
9 });
10
11 // Now safe to interact
12 await page.getByRole('button').click();
13});
4. Test Reactive State Changes
Test observable behavior from reactive updates:
typescript
1test('counter increments', async ({ page }) => {
2 await page.goto('/counter');
3
4 // Initial state
5 await expect(page.getByText('Count: 0')).toBeVisible();
6
7 // Click increment
8 await page.getByRole('button', { name: 'Increment' }).click();
9
10 // Reactive update (Playwright auto-waits for DOM change)
11 await expect(page.getByText('Count: 1')).toBeVisible();
12});
5. Mock Network Requests
Control external APIs for consistent tests:
typescript
1test('fetches and displays data', async ({ page }) => {
2 // Intercept API calls
3 await page.route('**/api/users', async (route) => {
4 await route.fulfill({
5 status: 200,
6 contentType: 'application/json',
7 body: JSON.stringify([{ id: 1, name: 'Test User' }])
8 });
9 });
10
11 await page.goto('/users');
12
13 // Assert mocked data is displayed
14 await expect(page.getByText('Test User')).toBeVisible();
15});
Common Vue Testing Patterns
Pattern: Testing Vue Router Navigation
typescript
1test('navigates to product details', async ({ page }) => {
2 await page.goto('/products');
3
4 // Click product link
5 await page.getByRole('link', { name: 'Product A' }).click();
6
7 // Wait for URL change (conditional, not timeout)
8 await expect(page).toHaveURL('/products/1');
9
10 // Assert component mounted with correct data
11 await expect(page.getByRole('heading', { name: 'Product A' })).toBeVisible();
12});
typescript
1test('validates form before submit', async ({ page }) => {
2 await page.goto('/contact');
3
4 // Leave required field empty
5 await page.getByLabel('Email').fill('');
6 await page.getByLabel('Message').fill('Hello');
7
8 // Try to submit
9 await page.getByRole('button', { name: 'Send' }).click();
10
11 // Error message should appear
12 await expect(page.getByText('Email is required')).toBeVisible();
13
14 // Form should not submit
15 await expect(page).toHaveURL('/contact');
16});
Pattern: Testing Modal Dialogs
typescript
1test('modal closes on cancel', async ({ page }) => {
2 await page.goto('/');
3
4 // Open modal
5 await page.getByRole('button', { name: 'Open Dialog' }).click();
6 await expect(page.getByRole('dialog')).toBeVisible();
7
8 // Close modal
9 await page.getByRole('button', { name: 'Cancel' }).click();
10
11 // Modal should disappear
12 await expect(page.getByRole('dialog')).not.toBeVisible();
13});
When to Load Reference Files
Load these strategically to optimize context usage:
references/e2e-patterns.md
- Building multi-page E2E workflows
- Implementing Page Object Model for Vue tests
- Testing complex user journeys
- Multi-step authentication flows
references/component-testing.md
- Testing Vue components in isolation
- Setting up experimental component testing
- Testing props, events, slots
- Testing composables with components
references/vue-specific-patterns.md
- Vue Router testing patterns
- Pinia state management testing
- Vue reactivity and computed properties
- Authentication testing in Vue
- Understanding wait patterns for Vue
references/best-practices.md
- Debugging flaky tests (and why timeouts aren't the answer)
- Selector strategies and troubleshooting
- API mocking patterns
- CI/CD configuration
- Performance optimization
Tips for Success
- Start with semantic locators - They're more stable and maintainable
- Never reach for timeouts first - If tests are flaky, investigate the root cause
- Test user behavior - Not implementation details or Vue internals
- Mock external APIs - For consistency and speed
- Run tests in parallel - Playwright supports parallel execution by default
- Use traces and videos - For debugging failed tests
- Review flaky tests immediately - Don't ignore intermittent failures
- Keep tests focused - One test should verify one behavior
- Set up CI/CD early - Use provided GitHub Actions workflow
- Reference the Vue-specific patterns - Understand how to wait for Vue correctly
File Structure
my-vue-app/
├── tests/
│ ├── e2e/
│ │ ├── login.spec.ts
│ │ ├── products.spec.ts
│ │ └── checkout.spec.ts
│ ├── fixtures/
│ │ ├── auth.ts
│ │ └── data.ts
│ └── pages/
│ ├── LoginPage.ts
│ ├── ProductsPage.ts
│ └── CheckoutPage.ts
├── playwright.config.ts
└── package.json
Resources
This skill includes references, templates, and scripts:
references/e2e-patterns.md
Comprehensive guide to E2E testing for Vue applications using Page Object Model and multi-page workflows.
references/component-testing.md
Guide to testing Vue components in isolation using Playwright's experimental component testing.
references/vue-specific-patterns.md
Vue-specific testing patterns including Router navigation, Pinia state management, reactivity testing, and proper wait strategies.
references/best-practices.md
Best practices including timeout anti-patterns, debugging flaky tests, selector strategies, and CI/CD setup.
assets/playwright.config.template.ts
Production-ready Playwright configuration optimized for Vue with Vite.
assets/workflows/playwright-vue.yml
GitHub Actions workflow for automated Playwright testing in CI/CD pipeline.
scripts/init-vue-playwright.ts
Setup script to initialize Playwright in an existing Vue project with proper configuration.