Course contentsShow
← JavaScript
Lesson 2706 of 2,72354. Testing in JavaScriptFree lesson

When to Mock and When Not To

Balance test isolation with realism; avoid over-mocking that hides integration issues.

When to Mock and When Not To

You'll learn: How to decide when mocking helps your tests and when it actually makes them less reliable.

The Core Principle

Mocking is a tool, not a default. The goal of testing is confidence that your code works in production. Over-mocking creates tests that pass in isolation but miss real integration problems—like a fire drill where everyone practices evacuating, but nobody checks if the doors actually open.

When to Mock

Mock external dependencies you can't control:

  • Network requests (APIs, databases)
  • File system operations
  • Third-party services
  • System time and timers

Mock to isolate the unit under test:

  • When testing complex logic that shouldn't fail because an unrelated module broke
  • When dependencies are slow or expensive

When NOT to Mock

Don't mock what you own: If you're testing a function that calls another function in your codebase, test them together. Mocking internal functions means you're testing your mocks, not your actual code flow.

Don't mock simple utilities: Date formatters, string helpers, math functions—these execute instantly and have no side effects. Mocking them adds complexity without benefit.

Don't mock just to avoid setup: If you mock everything because real objects are "annoying to create," your design might be the problem. That pain is feedback.

The Balance

Think of mocking like using a stunt double in a movie. Use one for dangerous scenes (external APIs), but if actors never interact with real props or sets, you lose authenticity. Integration tests with minimal mocking catch the bugs that unit tests with heavy mocking miss.

Key Takeaway: Mock external dependencies and slow operations, but test real interactions between your own modules—over-mocking creates false confidence and hides integration bugs.