Test doubles (mocking) replace real dependencies with controlled substitutes that make tests fast, deterministic, and isolated. Types: Mock (verifies interactions were made), Stub (returns canned responses), Spy (wraps real implementation, tracks calls), Fake (working implementation, e.g. in-memory DB), Dummy (placeholder with no behaviour). Understanding when to use each type prevents brittle tests that over-specify implementation details while catching real bugs.
Code comparison of different test double types in Jest.
Mocks encode 'was this specific method called with these exact arguments?' Fakes encode 'does the system behave correctly?' Fakes produce fewer false failures when implementation details change.
If a test mocks 5+ dependencies, the class under test violates SRP (single responsibility) and has too many dependencies. That test complexity is telling you to refactor, not add more mocks.
Tests that call new Date() or Math.random() directly are non-deterministic. Inject a clock/random dependency and mock it: jest.setSystemTime(new Date('2025-01-01')). Always reproducible.
Sign in to share your feedback and join the discussion.