Next.js cung cấp helper next/jest để tự lo cấu hình (transform SWC, mock CSS/ảnh, env).
js
// jest.config.js
const nextJest = require('next/jest')
const createJestConfig = nextJest({ dir: './' })
module.exports = createJestConfig({
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
})Dùng cho unit / component test: render Client Component bằng RTL, query theo role, fire event.
Tại sao async Server Components là vấn đề: chúng là async function trả Promise và có thể await data/fetch thật trên server. Jest (jsdom) không có môi trường server đầy đủ để resolve các luồng RSC này. Khuyến nghị chính thức:
- Server Components async → test bằng E2E (Playwright) vì chúng cần môi trường server thật.
- Logic thuần (helpers, sync components) → unit test với Jest.
Lưu ý: RTL không chạy được trên Vitest/Jest cho async RSC — đừng cố mock cả pipeline, đẩy phần đó sang E2E.