Nâng CaoTesting iconTesting

Test isolation: tại sao quan trọng và cách đảm bảo?

Test isolation đảm bảo tests không phụ thuộc thứ tự — dùng jest.resetAllMocks() trong afterEach, transaction rollback cho DB tests, tránh global state mutation.

  • Test isolation đảm bảo mỗi test chạy độc lập — không phụ thuộc vào thứ tự, không share state với tests khác.
  • Tại sao quan trọng: test order-dependent là flaky (pass individually, fail khi chạy cùng); shared state làm debug khó (failing test có thể do test khác gây ra).
  • Kỹ thuật isolation: Module mocks: jest.resetModules() trong beforeEach để reset module registry — cần thiết khi mock modules có side effects; Environment reset: jest.clearAllMocks() (reset call count), jest.resetAllMocks() (clear implementations cũng), jest.restoreAllMocks() (restore spies); Database isolation: transaction rollback sau mỗi test (Prisma: prisma.$transaction với rollback trong afterEach), hoặc truncate tables; Test-scoped servers: mỗi test suite tạo Express instance riêng thay vì shared global app. --runInBand flag chạy tests sequential (không parallel) để debug isolation issues — nếu test pass với --runInBand nhưng fail parallel, đó là shared state bug.
  • Jest worker isolation: mỗi file chạy trong separate Node.js worker — file-level isolation tốt; within file mới cần manual isolation.

Pitfall: global variable mutations trong test không cleanup → leak sang test tiếp theo.

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

Mở danh sách Testing