Skip to content
Go back

Using Vitest and Playwright for Full-Stack Testing

Using Vitest and Playwright for Full-Stack Testing

Introduction

Combining Vitest for fast unit tests with Playwright for reliable end-to-end tests ensures thorough coverage of frontend and backend.

Prerequisites

Step 1: Install Dependencies

pnpm add -D vitest @testing-library/vue jsdom @playwright/test

Step 2: Vitest Configuration

Create vitest.config.ts:

import { defineConfig } from 'vitest/config';

export default defineConfig({
  test: {
    globals: true,
    environment: 'jsdom',
    coverage: {
      reporter: ['text', 'lcov'],
    },
    setupFiles: ['./test/setup.ts'],
  },
});

Create test/setup.ts:

import '@testing-library/jest-dom';

Write a Vue component test test/Counter.spec.ts:

import { render, fireEvent } from '@testing-library/vue';
import Counter from '../src/components/Counter.vue';

test('increments count on button click', async () => {
  const { getByText } = render(Counter);
  const button = getByText('Count is: 0');
  
  await fireEvent.click(button);
  getByText('Count is: 1');
});

Run unit tests:

pnpm vitest run --coverage

Step 3: Playwright Configuration

Initialize Playwright:

npx playwright install

Create playwright.config.ts:

import { defineConfig, devices } from '@playwright/test';

export default defineConfig({
  testDir: 'e2e',
  timeout: 60000,
  retries: 1,
  use: {
    baseURL: 'http://localhost:3000',
    headless: true,
    viewport: { width: 1280, height: 720 },
    ignoreHTTPSErrors: true,
    video: 'on-first-retry',
  },
  projects: [
    { name: 'chromium', use: { ...devices['Desktop Chrome'] } },
    { name: 'firefox', use: { ...devices['Desktop Firefox'] } },
    { name: 'webkit', use: { ...devices['Desktop Safari'] } },
  ],
});

Write an E2E test e2e/login.spec.ts:

import { test, expect } from '@playwright/test';

test('user can log in', async ({ page }) => {
  await page.goto('/login');
  await page.fill('input[name="email"]', 'user@example.com');
  await page.fill('input[name="password"]', 'password123');
  await page.click('button[type="submit"]');
  
  await expect(page).toHaveURL('/dashboard');
  await expect(page.getByText('Welcome,')).toBeVisible();
});

Run E2E tests:

pnpm playwright test

Step 4: CI Integration

Example GitHub Actions snippet:

- name: Run Vitest
  uses: pnpm/action-setup@v2
  with:
    version: 8
- run: pnpm install
- run: pnpm vitest run --coverage

- name: Run Playwright
  uses: microsoft/playwright-github-action@v1
  with:
    install: true
- run: pnpm playwright test

Summary

Using Vitest and Playwright together provides fast unit testing and robust end-to-end testing, ensuring high code quality and reliability across the full stack.


Share this post on:

Previous Post
Automating Changelog Generation with Changesets
Next Post
Setting Up a Monorepo with Turborepo and pnpm