Test Isolation with Test Doubles: Best Practices
Test isolation means each test runs independently—no shared state, no order dependencies, no surprise failures caused by other tests. Test doubles make isolation possible by replacing real dependencies with controlled stand-ins. But using them well requires discipline. Done carelessly, test doubles create isolation in name only, while tests remain brittle and hard to maintain.
This guide covers the best practices for test isolation using test doubles—what to isolate, how to isolate it, and when to stop.
Why Isolation Matters
Without isolation:
- Tests fail intermittently because they share state
- Tests pass locally but fail in CI because the environment differs
- One failing test causes cascading failures in others
- Debugging requires understanding the entire test suite, not just one test
With proper isolation:
- Each test is its own unit of proof
- Tests run in any order, in parallel, on any machine
- Failures point to specific code, not mysterious interactions
Test doubles are the primary tool for achieving this.
What to Isolate (And What Not To)
Isolate: External systems
Any I/O that crosses a process boundary should be isolated in unit tests:
- Databases
- HTTP APIs
- File systems
- Message queues
- Email/SMS services
- Clock and time
// Without isolation: test depends on a real running database
it("saves user", async () => {
const user = await userService.create({ name: "Alice" }); // hits real DB
expect(user.id).toBeDefined();
});
// With isolation: test is independent
it("saves user", async () => {
const repo = new InMemoryUserRepository();
const service = new UserService(repo);
const user = await service.create({ name: "Alice" });
expect(user.id).toBeDefined();
});Isolate: Non-deterministic behavior
Anything that changes between runs—timestamps, random values, network calls—should be controlled.
// Isolate the clock
const clock = jest.useFakeTimers();
clock.setSystemTime(new Date("2025-01-01T00:00:00Z"));
const result = service.generateToken(userId);
expect(result.expiresAt).toBe("2025-01-08T00:00:00Z"); // 7 days later
clock.useRealTimers();Don't isolate: Your own code
Unit tests shouldn't mock internal collaborators—code your module owns. If OrderService uses a private PriceCalculator class, don't mock PriceCalculator. Let them work together. Only mock at the real boundary.
// Bad: mocking internal logic
const priceCalcMock = jest.spyOn(orderService, "_calculatePrice");
// This tests the outline, not the behavior
// Good: mock at the real boundary
const paymentGatewayMock = { charge: jest.fn().mockResolvedValue({ success: true }) };
const service = new OrderService(paymentGatewayMock);Best Practice 1: One Test Double Per Boundary
Identify the real integration boundaries—places where your code talks to the outside world. Create one test double per boundary, no more.
// Service has two boundaries: repo (DB) and emailer (SMTP)
class UserRegistrationService {
constructor(userRepo, emailer) { ... }
}
// Tests use one double per boundary
const repo = new InMemoryUserRepository();
const emailer = { send: jest.fn() };
const service = new UserRegistrationService(repo, emailer);Don't add doubles for every internal method call. That's over-isolation.
Best Practice 2: Reset State Between Tests
Shared test double state causes order-dependent tests—one of the most painful bugs to diagnose.
// Bad: shared mock accumulates state across tests
const emailMock = { send: jest.fn() };
const service = new OrderService(emailMock);
it("sends email on order", async () => {
await service.place(order1);
expect(emailMock.send).toHaveBeenCalledTimes(1); // passes
});
it("sends one email per order", async () => {
await service.place(order2);
expect(emailMock.send).toHaveBeenCalledTimes(1); // FAILS: count is 2
});// Good: reset or recreate in beforeEach
let emailMock;
beforeEach(() => {
emailMock = { send: jest.fn() };
});Or with Jest's automatic reset:
// jest.config.js
{
clearMocks: true, // clears mock.calls and mock.instances between tests
resetMocks: true, // also resets return values
restoreMocks: true // restores spied methods
}Best Practice 3: Inject Dependencies, Don't Reach for Them
Test doubles only work when dependencies are injected. If your code creates its own dependencies, you can't replace them.
// Bad: dependency is created internally — can't replace it
class OrderService {
constructor() {
this.emailer = new SmtpEmailer(); // hardcoded
}
}
// Good: dependency is injected — can be replaced
class OrderService {
constructor(emailer) {
this.emailer = emailer;
}
}Dependency injection is a prerequisite for testability. Without it, you're forced into module-level mocking (fragile) or skipping unit tests entirely.
Best Practice 4: Match the Double to the Question
Each test answers one question. The type of double should match what question you're asking.
| Question | Double | Reason |
|---|---|---|
| What does my function return? | Stub | Controls input, asserts on output |
| Did my function call X? | Mock/Spy | Captures outbound calls |
| Does my function handle state correctly? | Fake | Supports stateful interactions |
| Is this param irrelevant? | Dummy | Satisfies interface without contribution |
Don't default to mocks for everything. A test full of jest.fn() calls where only the final assertion matters often should be using stubs.
Best Practice 5: Test the Boundary, Not the Implementation
Mocks tied to private methods or internal state break when you refactor—even when behavior doesn't change.
// Fragile: tests implementation details
it("calls _formatAddress before saving", () => {
const spy = jest.spyOn(service, "_formatAddress");
service.save(user);
expect(spy).toHaveBeenCalled();
});
// Robust: tests observable behavior
it("saves user with formatted address", async () => {
await service.save({ name: "Alice", address: "123 main st" });
const saved = await repo.findById(1);
expect(saved.address).toBe("123 Main St"); // formatted
});The second test survives any internal refactoring as long as the formatting behavior is preserved.
Best Practice 6: Contract-Test Your Fakes
Fakes diverge from reality over time. When the real dependency changes its behavior, your fake might not keep up—and tests give false confidence.
// Contract tests: same tests run against both real and fake
const implementations = [
{ name: "real", repo: new PostgresUserRepository() },
{ name: "fake", repo: new InMemoryUserRepository() },
];
implementations.forEach(({ name, repo }) => {
describe(`${name} UserRepository`, () => {
it("returns null for missing id", async () => {
expect(await repo.findById(999)).toBeNull();
});
it("persists and retrieves user", async () => {
await repo.save({ id: 1, name: "Alice" });
const user = await repo.findById(1);
expect(user.name).toBe("Alice");
});
});
});Run the real implementation tests in integration test suites (against actual infrastructure). Run fake tests in unit tests. Keep them in sync.
Best Practice 7: Avoid Testing Third-Party Libraries
Don't write tests that verify third-party library behavior. They know how to test themselves. Your tests should verify your usage of those libraries.
// Bad: testing Axios behavior
it("axios makes a GET request", async () => {
const response = await axios.get("https://api.example.com/users");
expect(response.status).toBe(200);
});
// Good: testing your code's behavior when using the library
it("user service returns users on success", async () => {
const httpClient = { get: jest.fn().mockResolvedValue({ data: [{ id: 1, name: "Alice" }] }) };
const service = new UserService(httpClient);
const users = await service.listUsers();
expect(users).toHaveLength(1);
});Isolation Has Limits
Proper test isolation in unit tests doesn't mean you're done. Isolated tests prove each unit works in a controlled environment. They don't prove:
- Units work together correctly
- Your stubs accurately reflect external system behavior
- The real database query does what you expect
That's where integration tests and end-to-end tests complete the picture.
HelpMeTest runs end-to-end tests against your real application in plain English. When isolated unit tests pass but users report bugs, end-to-end tests catch the integration failures your test doubles can't see.
Isolation Checklist
Before shipping a test suite, verify:
- Tests can run in any order without failure
- Tests can run in parallel without failure
- No test modifies shared state that others read
- Each test uses fresh test doubles (or cleared state)
- Dependencies are injected, not hardcoded
- Mocks target real boundaries, not internal methods
- Fakes are contract-tested against real implementations
- Non-determinism (time, randomness) is controlled
Summary
Good test isolation:
- Replaces external boundaries with doubles, not internal collaborators
- Resets double state between tests
- Uses dependency injection to make replacement possible
- Matches double type to what the test is actually verifying
- Tests behavior at observable boundaries, not implementation details
- Validates fakes with contract tests
- Accepts that isolated tests are necessary but not sufficient—end-to-end tests complete coverage