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

Balancing Test Granularity

Decide when to write focused unit tests versus broader integration tests for effective coverage.

Balancing Test Granularity

You'll learn: How to decide between writing tightly focused unit tests and broader integration tests for optimal test coverage and maintainability.

The Test Granularity Spectrum

Test granularity refers to the scope of what you're testing. Unit tests examine individual functions or methods in isolation—testing one thing at a time. Integration tests verify that multiple components work together correctly. Finding the right balance is crucial: too granular and you'll drown in trivial tests; too broad and you'll struggle to pinpoint failures.

When to Write Unit Tests

Choose unit tests when:

  • Testing pure functions with clear inputs/outputs
  • Validating complex logic or algorithms
  • Ensuring edge cases are covered (nulls, empty arrays, boundary values)
  • You need fast feedback during development

Unit tests are your first line of defense. They run quickly and pinpoint exactly what broke.

When to Write Integration Tests

Choose integration tests when:

  • Testing how modules communicate
  • Verifying API routes with database calls
  • Checking that configuration correctly wires components together
  • Testing user-facing workflows that span multiple functions

Integration tests catch issues that unit tests miss—like incorrect assumptions about how components interact.

The Practical Balance

Think of it like building inspection: unit tests check each brick's quality, while integration tests verify the wall stands upright. You need both. A common ratio is 70-80% unit tests, 20-30% integration tests, though this varies by project.

Don't test implementation details obsessively—test behavior. If refactoring breaks dozens of tests without changing functionality, your tests are too granular. If one failure gives you no clue where to look, they're too broad.

Key Takeaway: Balance focused unit tests that run fast and catch specific bugs with integration tests that verify components work together—prioritize unit tests for logic, integration tests for workflows.