🌙
☀️ Dark
PART 22

Testing

Unit, integration, mocking, test isolation.

Intermediate 45 min read

Revision Sheet

  • Unit Test: Isolated logic. Fast.
  • Integration Test: Multiple units together (DB, Cache). Moderate.
  • E2E Test: Full system via UI. Slow.
  • Mock: Fake dependency that records usage.
  • Test Isolation: Tests must not affect each other.

Connections

Connects to: CI/CD (Part 23), Database Design (Part 15), and Software Architecture (Part 20).

🏠 Curriculum NextVolume 2

Mini Project (20-30 min)

▶ View Solution

Create a simple Shopping Cart class. Write tests for adding items, calculating totals with tax, and applying discount codes. Use mocks for an external inventory API.

Bigger Project (1-2 hours)

Apply all concepts from this volume to build a comprehensive feature.

▶ View Solution
typescript
// Example project code here

Interview Questions

Easy: What is the difference between a mock and a stub?

A stub is a dummy piece of code that lets the test run, returning hardcoded data. A mock is a stub that also records how it was called so you can assert against it later.

Medium: Why are E2E tests considered brittle?

Because they rely on the UI structure. If a CSS class or button ID changes, the E2E test fails even if the business logic works perfectly.

Hard: How do you handle database state in integration testing?

Typically by running a clean database instance (like testcontainers). You can either run DB migrations before all tests, and wrap each test in a transaction that rolls back at the end, or truncate all tables between tests.

Senior: When would you NOT write a unit test?

When the code has no pure logic and is purely wiring (e.g., a controller that just passes data to a service). In those cases, an integration test provides much higher ROI than a unit test with 10 mocks.