← Lessons

quiz vs the machine

Silver1120

Frontend

Mocking Network Requests

Intercept HTTP so tests are fast, deterministic, and offline.

4 min read · intro · beat Silver to climb

Why mock the network

Real requests are slow, flaky, and depend on a running backend. Mocking lets you control responses so tests are deterministic and run offline.

Where to intercept

  • Network layer intercept at the HTTP boundary, for example with a request handler that catches fetch calls. The component code stays unchanged.
  • Module level replace the data fetching module with a fake. Faster to set up but couples tests to internal structure.

Intercepting at the network layer is usually best because the code under test runs unmodified.

Cover the cases

  • A successful response with realistic data.
  • An error response such as a 500 to test failure UI.
  • A slow or pending response to test loading states.

Keep mock data close to real shapes so tests catch contract mismatches.

Key idea

Mock at the network boundary and cover success, error, and loading to test all UI states.

Check yourself

Answer to earn rating on the learn ladder.

1. Why is intercepting at the network layer often preferred?

2. Which scenario should a network mock NOT bother covering?