5 tháng 11, 2025 · 11 phút đọc

Testing strategy cho frontend: unit, integration và E2E — cân bằng đúng

Testing pyramid hay testing trophy? Vitest, Testing Library và Playwright — setup và strategy thực tế cho Next.js app.

Testing strategy cho frontend: unit, integration và E2E — cân bằng đúng

Testing strategy không phải là 'coverage càng cao càng tốt'. Mục tiêu là confidence với minimum maintenance burden. Nhiều teams viết quá nhiều unit tests cho implementation details, và quá ít integration tests cho user flows.

Testing Trophy: Kent C. Dodds' approach

Testing Trophy ưu tiên integration tests nhiều nhất, unit tests ít hơn, E2E tests một số critical paths. Nguyên tắc: 'Test behavior, not implementation'. Viết tests theo cách user dùng app — render component, interact, assert visible outcome.

Ví dụ: đừng test internal state của component. Thay vào đó, render với Testing Library, click button, assert DOM output thay đổi đúng. Refactor implementation không break tests — đây là dấu hiệu test quality tốt.

Developer writing tests on laptop
Good tests cho confidence khi refactor, không phải obstacles

Vitest: unit và integration tests

Vitest là Vite-native test runner — nhanh hơn Jest đáng kể nhờ native ESM và parallel runs. Compatible với Jest API nên migration dễ. jsdom environment cho DOM testing. Coverage với v8 provider không cần babel.

Setup với React Testing Library: render, screen queries (getByRole, getByText — accessible queries ưu tiên), userEvent để simulate interactions. MSW (Mock Service Worker) để mock API calls ở network level — realistic hơn mocking fetch.

Playwright: E2E testing

Playwright là E2E testing framework mạnh nhất hiện tại. Cross-browser (Chromium, Firefox, WebKit), parallel execution, auto-waiting, codegen để record tests. Component testing mode cho test components trong real browser.

What to test at each level

Unit tests: pure functions, utility logic, complex business rules. Integration tests: component interactions, form flows, data fetching mocked. E2E tests: critical user journeys (signup, checkout, core feature). Điều chỉnh theo risk và change frequency.

Test trong CI

Chạy unit + integration trên mọi PR. E2E chỉ trên main branch hoặc staging để tiết kiệm CI time. Shard E2E tests across multiple machines. Screenshot/video artifacts khi fail để debug dễ hơn.