Testing ứng dụng Next.js
Test gì ở tầng nào trong Next.js: unit test DAL/action, component test cho Client Component, giới hạn khi test async Server Component, E2E với Playwright chạy trên bản build, và CI.
Next.js trộn server và client trong cùng một cây, nên cách test của SPA không còn đủ: async Server Component chưa được các công cụ unit test hỗ trợ tốt, Server Action là endpoint cần test bảo mật, và nhiều hành vi (cache, streaming) chỉ đúng trên bản build.
🎯 Mục tiêu học tập
- Chia chiến lược test cho ứng dụng Next.js
- Unit test Server Action và DAL, kể cả các ca bị từ chối quyền
- Component test Client Component với Testing Library
- E2E bằng Playwright trên
next build - Chạy toàn bộ trong CI với database thật (container)
Test gì ở đâu
| Đối tượng | Tầng test | Công cụ |
|---|---|---|
| Hàm thuần, schema Zod, permission | Unit | Vitest |
| DAL, Server Action (gọi như hàm) | Integration với DB thật | Vitest + Testcontainers/Postgres trong Docker |
| Client Component | Component | Vitest + Testing Library + MSW |
| Server Component đồng bộ | Component | Testing Library (render được) |
| Async Server Component, streaming, cache, proxy, luồng người dùng | E2E | Playwright trên next build && next start |
Async Server Component hiện chưa render được ổn định trong Vitest/Jest — tài liệu Next.js khuyến nghị test chúng bằng E2E. Cách giảm phụ thuộc: tách logic dữ liệu ra DAL (unit test được) và giữ component mỏng.
Test Server Action
// app/posts/actions.test.ts
import { vi, test, expect, beforeEach } from 'vitest';
vi.mock('next/cache', () => ({ updateTag: vi.fn(), revalidateTag: vi.fn(), refresh: vi.fn() }));
vi.mock('next/navigation', () => ({ redirect: vi.fn(() => { throw new Error('NEXT_REDIRECT'); }) }));
vi.mock('@/lib/dal', () => ({ verifySession: vi.fn() }));
import { deleteComment } from './actions';
import { verifySession } from '@/lib/dal';
beforeEach(async () => { await resetDb(); await seed(); });
test('không cho xoá bình luận của người khác', async () => {
vi.mocked(verifySession).mockResolvedValue({ userId: 'bob', role: 'user' });
await expect(deleteComment('comment-of-alice')).rejects.toThrow('Forbidden');
expect(await countComments()).toBe(1);
});
test('admin xoá được', async () => {
vi.mocked(verifySession).mockResolvedValue({ userId: 'admin', role: 'admin' });
await deleteComment('comment-of-alice');
expect(await countComments()).toBe(0);
});
Bộ test bảo mật tối thiểu cho mỗi action: chưa đăng nhập, sai quyền trên tài nguyên, dữ liệu sai schema, giá trị biên.
Component test
// Client Component dùng useRouter cần mock next/navigation
vi.mock('next/navigation', () => ({
useRouter: () => ({ replace: vi.fn(), push: vi.fn() }),
usePathname: () => '/shop',
useSearchParams: () => new URLSearchParams('sort=price'),
}));
test('đổi sắp xếp cập nhật URL', async () => {
const user = userEvent.setup();
render(<Filters />);
await user.selectOptions(screen.getByRole('combobox', { name: /sắp xếp/i }), 'new');
// kiểm tra router.replace được gọi với ?sort=new
});
E2E với Playwright
// playwright.config.ts
export default defineConfig({
webServer: { command: 'npm run build && npm run start', port: 3000, reuseExistingServer: !process.env.CI, timeout: 180_000 },
use: { baseURL: 'http://localhost:3000', trace: 'on-first-retry' },
projects: [{ name: 'setup', testMatch: /auth\.setup\.ts/ }, { name: 'chromium', dependencies: ['setup'], use: { storageState: '.auth/user.json' } }],
});
// e2e/edit-price.spec.ts
test('admin sửa giá, trang sản phẩm thấy ngay giá mới', async ({ page }) => {
await page.goto('/admin/products/p1');
await page.getByLabel('Giá').fill('150000');
await page.getByRole('button', { name: 'Lưu' }).click();
await page.goto('/products/ao-thun');
await expect(page.getByTestId('price')).toHaveText('150.000 đ'); // kiểm chứng updateTag hoạt động
});
E2E là nơi duy nhất kiểm tra được cache + revalidation, streaming, proxy redirect, và hydration không lỗi (lắng nghe
page.on('console') để fail test khi có cảnh báo hydration).
CI
jobs:
test:
runs-on: ubuntu-latest
services:
postgres:
image: postgres:17
env: { POSTGRES_PASSWORD: test }
ports: ['5432:5432']
options: --health-cmd pg_isready --health-interval 5s
env:
DATABASE_URL: postgres://postgres:test@localhost:5432/postgres
steps:
- uses: actions/checkout@v4
- uses: actions/setup-node@v4
with: { node-version: 22, cache: npm }
- run: npm ci
- run: npx tsc --noEmit && npx eslint .
- run: npm run db:migrate && npx vitest run
- run: npx playwright install --with-deps chromium && npx playwright test
- uses: actions/upload-artifact@v4
if: failure()
with: { name: playwright-report, path: playwright-report }
Next.js 16 đã bỏ lệnh next lint — chạy ESLint trực tiếp (hoặc Biome).
🚩 Sai lầm hay gặp
- Chỉ test 'happy path' của Server Action.
- Chạy E2E trên
next dev(cache và streaming khác production). - Mock database ở mọi test — bỏ lỡ lỗi SQL và ràng buộc.
🏋️ Bài tập thực hành
20 test DAL/action với Postgres thật (gồm 8 test từ chối quyền), 10 component test, 5 E2E (đăng nhập, CRUD, sửa giá thấy ngay, modal route, i18n redirect). Chạy trong GitHub Actions, đính kèm Playwright trace khi lỗi.
📚 Tài nguyên học tập
-
Next.js — TestingVitest, PlaywrightDocs
-
Testcontainers for NodeDB thật trong testLibrary
✅ Tự đánh giá hoàn thành
- Tôi biết test async Server Component ở tầng nào và vì sao
- Tôi viết được test bảo mật cho Server Action
- Tôi chạy E2E trên bản build có DB thật