#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
- Set up Playwright.
- Write a test that visits your Homepage.
- Check if your
<h1>contains the correct text. - Run
npx playwright test. - Watch the headless browser pass the test!
See you tomorrow for the Capstone Project Part I! ποΈ