#nextjs #testing #vitest #playwright #e2e

Day 28 β€” Testing: Vitest & Playwright

🧭 Day 28 β€” Testing: Vitest & Playwright

Zero to Hero β€” Hands-on Next.js Tutorial

β€œIt works on my machine” is not a testing strategy. We need automated tests.


🟦 1. Unit Testing (Vitest)

Vitest is a blazing fast replacement for Jest. It works natively with Vite (which Next.js doesn’t use, but the config is compatible).

Setup:

npm install -D vitest @testing-library/react @testing-library/dom jsdom

Create vitest.config.ts and src/components/Button.test.tsx:

import { render, screen } from '@testing-library/react'
import Button from './Button'
import { describe, expect, test } from 'vitest'
 
describe('Button', () => {
  test('renders correctly', () => {
    render(<Button>Click Me</Button>)
    expect(screen.getByRole('button')).toHaveTextContent('Click Me')
  })
})

🟩 2. E2E Testing (Playwright)

Unit tests check functions. E2E tests check User Flows (Clicking, Navigating). Playwright is the modern standard (better than Cypress for speed/reliability).

Setup:

npm init playwright@latest

Example Test (tests/example.spec.ts):

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

test('has title', async ({ page }) => {
  await page.goto('http://localhost:3000'); // Visit your local server
  
  // Expect a title "to contain" a substring.
  await expect(page).toHaveTitle(/Next.js/);
  
  // Click the login button
  await page.click('text=Login');
  
  // Expect to be on login page
  await expect(page).toHaveURL(/.*login/);
});

🟧 3. Integration with CI

The goal is to run these tests automatically on GitHub Actions whenever you push code. If a test fails, the Pull Request cannot be merged.


πŸ§ͺ Challenge: Day 28

  1. Set up Playwright.
  2. Write a test that visits your Homepage.
  3. Check if your <h1> contains the correct text.
  4. Run npx playwright test.
  5. Watch the headless browser pass the test!

See you tomorrow for the Capstone Project Part I! πŸ—οΈ