Frontend Patterns

Pattern

API Mocking

Replace real API calls with controlled responses for predictable testing.

Testing Intermediate

API Mocking

Problem

Tests that depend on real APIs are slow, flaky, and fragile. They fail when the network is down, break when backend endpoints change, and make it impossible to test error states or edge cases. Running the test suite requires a fully functioning backend, slowing down development and CI pipelines.

Solution

Intercept HTTP requests during tests and return predefined responses that simulate success, errors, and edge cases. This decouples your tests from the backend, making them fast, reliable, and capable of testing scenarios that are difficult to reproduce with a real API.

Example

This example demonstrates mocking the fetch API to return predictable test data, eliminating the need for a real backend during testing.

// Replace the global fetch function with a mock implementation
global.fetch = jest.fn(() =>
  Promise.resolve({
    // Mock the json() method to return our test data
    json: () => Promise.resolve({ id: 1, name: 'Test User' })
  })
);

test('loads user data', async () => {
  // Call the function that uses fetch internally
  const user = await fetchUser(1);

  // Verify the mocked data is returned correctly
  expect(user.name).toBe('Test User');
});

Benefits

  • Decouples frontend tests from backend availability and network reliability.
  • Enables testing of error states and edge cases that are hard to reproduce.
  • Makes tests run faster by eliminating actual network requests.
  • Allows development to continue even when backend APIs are unavailable.
  • Creates predictable test scenarios with complete control over responses.

Tradeoffs

  • Mock responses can drift from actual API behavior over time.
  • Doesn’t test actual network conditions or integration issues.
  • Requires maintenance to keep mocks synchronized with backend changes.
  • Can create false confidence if mocks don’t match real API responses.
  • May miss issues related to CORS, authentication, or network timeouts.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.