Testing
Frontend testing — unit, integration, and e2e tests
What you'll learn
Understand the testing pyramid: unit, integration, and e2e tests
Write unit tests with Vitest and React Testing Library
Test user interactions and behavior instead of implementation details
Mock external dependencies at the network boundary using MSW
Integrate tests into CI pipelines for consistent quality gates
Measure code coverage and identify untested critical paths
Testing ensures your code works correctly and stays working.
Testing Pyramid
╱ E2E ╲ Few, slow, high confidence
╱ Integration ╲ Medium count
╱ Unit Test ╲ Many, fast, low confidence
Unit Tests (Vitest + React Testing Library)
import { render, screen, fireEvent } from "@testing-library/react"
import { describe, it, expect } from "vitest"
import Counter from "./Counter"
describe("Counter", () => {
it("starts at 0", () => {
render(<Counter />)
expect(screen.getByText("0")).toBeDefined()
})
it("increments on click", () => {
render(<Counter />)
fireEvent.click(screen.getByText("+"))
expect(screen.getByText("1")).toBeDefined()
})
})
Tools
- Vitest — Fast unit test runner
- React Testing Library — Component tests
- Playwright — E2E browser tests
- MSW — Mock API responses
Best Practices
- Test behavior, not implementation
- Avoid testing framework internals
- Write tests that resemble user interactions
- Mock at the network boundary (MSW)
- Run tests in CI
Next Steps
Key Takeaways
The testing pyramid recommends many fast unit tests, fewer integration tests, and even fewer slow e2e tests
React Testing Library encourages testing behavior (what the user sees and does) not implementation details
Mock at the network boundary using MSW rather than mocking individual modules or functions
Vitest offers near-perfect Jest compatibility but runs significantly faster thanks to Vite's bundler
CI integration ensures tests run on every push and PR, preventing regressions from reaching production