Trung BìnhNode.js iconNode.js

Cách viết unit tests cho Node.js API với Jest?

  • Test pyramid cho Node.js API: unit tests (service/utils logic) → integration tests (controller + real DB) → e2e tests (full HTTP).
  • Controller testing với supertest: const res = await request(app).post('/users').send({ email: 'test@test.com' }); expect(res.status).toBe(201) — không cần start server, supertest inject request trực tiếp.
  • Service testing: mock DB layer với jest.mock('../db')(db.findUser as jest.Mock).mockResolvedValue({ id: 1 }) — test business logic độc lập với DB.
  • Middleware testing: gọi middleware với mock req, res, next objects — verify next() được gọi hay res.status() được set.
  • Integration tests: dùng test DB riêng (TEST_DATABASE_URL), chạy migrations trước test suite, truncate tables giữa tests (afterEach).
  • Mock strategies: jest.mock() cho modules, jest.spyOn() cho methods, jest.useFakeTimers() cho time-dependent code.
  • Test database setup: globalSetup chạy migration một lần, beforeEach truncate data, afterAll disconnect.
  • Coverage: jest --coverage + coverageThreshold: { global: { lines: 80 } } enforce minimum.

Pitfall: không isolate tests → test order dependent failures; mock tất cả external calls (HTTP, email) để tests deterministic.

Xem toàn bộ Node.js cùng filter theo level & chủ đề con.

Mở danh sách Node.js