The Testing Pyramid: Strategy

The Testing Pyramid: Strategy in JavaScript: Imagine you are building a car. 1. Unit Test: You test a single spark plug.

Concept Explanation

Imagine you are building a car.

  1. Unit Test: You test a single spark plug. Does it spark? (Testing a single function).
  2. Integration Test: You test if the spark plug works with the engine block. (Testing two components together).
  3. E2E Test: You drive the car for 10 miles. Does it actually get you from A to B? (Testing the whole website).

Professional developers follow the Pyramid: you should have thousands of Unit tests, hundreds of Integration tests, and only a few dozen E2E tests.


Why a Pyramid, Not an Ice-Cream Cone?

The shape is deliberate. Unit tests are cheap (milliseconds to run) and precise (they point at the exact broken function). E2E tests are slow (they boot a whole browser) and flaky (a network blip fails them). Invert the pyramid — mostly E2E, few units — and your suite becomes slow, brittle, and useless at pinpointing bugs.


Common Mistakes

  • All E2E: Testing everything through the browser feels thorough but is agonizingly slow and flaky.
  • Testing Implementation: Don't assert how code works internally — test what it produces. Refactors shouldn't break good tests.
  • Chasing 100%: The last 10% of coverage often costs more than it's worth. Cover the risky logic well.

Best Practices

  • Isolated Tests: A test for "Addition" should not fail because the "Database" is down. Use Mocks to fake the parts you aren't testing.
  • Descriptive Names: test('it should add 2 numbers') is much better than test('math test').
  • Code Coverage: Use tools to see which lines of your code have NO tests. Aim for 80%+, but don't obsess over reaching 100%.

Practice Exercises

  1. The Analyst: Pick an app you use every day (like Gmail). List 3 "Unit" tests and 1 "E2E" test you would write for it.
  2. The Bug Hunter: Research why tests make you faster as a developer, even though they take time to write.
  3. Mocks vs Stubs: Research the difference between a "Mock" and a "Stub" in testing.