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.$transactionvớ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.--runInBandflag chạy tests sequential (không parallel) để debug isolation issues — nếu test pass với--runInBandnhư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.
- Lưu ý: global variable mutations trong test không cleanup → leak sang test tiếp theo.
Test isolation ensures tests don't depend on order — use jest.resetAllMocks() in afterEach, transaction rollback for DB tests, avoid global state mutations.
- Test isolation ensures each test runs independently — no ordering dependencies, no shared state.
- Why it matters: order-dependent tests are flaky (pass individually, fail together); shared state makes debugging hard (a failing test may be caused by a different test).
- Isolation techniques: Module mocks:
jest.resetModules()in beforeEach to reset the module registry — needed when mocked modules have side effects; Environment reset:jest.clearAllMocks()(reset call counts),jest.resetAllMocks()(also clears implementations),jest.restoreAllMocks()(restores spies); Database isolation: transaction rollback after each test (Prisma:prisma.$transactionwith rollback in afterEach), or truncate tables; Test-scoped servers: each test suite creates its own Express instance instead of a shared global app. - The
--runInBandflag runs tests sequentially to debug isolation issues — if tests pass with--runInBandbut fail in parallel, it's a shared state bug. - Jest worker isolation: each file runs in a separate Node.js worker — good file-level isolation; within a file, manual isolation is still needed.
Pitfall: global variable mutations in a test that aren't cleaned up leak into subsequent tests.