Smart Systems for Home

Plain how-to guides for smart home, security and home Wi-Fi

TypeScript HTTP Client: What to Test

· 5 min read · Home Tech

In this article
  1. Why Testing the HTTP Client Matters
  2. What Exactly to Test in Your Client
  3. How to Structure Tests for an HTTP Client
  4. Common Pitfalls and Misconceptions
  5. Choosing the Right Testing Tools
  6. Comparing Mocking Approaches: MSW vs. Simple Mocks
  7. Costs and Maintenance of Testing
  8. Safety and Security Considerations
  9. Frequently Asked Questions

When building a TypeScript application, the HTTP client is the bridge to your backend, and testing it properly means verifying that it sends the right requests, handles responses correctly, and fails gracefully. You should test request construction (URL, method, headers, body), response parsing (status codes, JSON, errors), timeout and cancellation behavior, and the retry/error-handling logic you've implemented. This article explains what to focus on, how to structure those tests, and common pitfalls to avoid.

Why Testing the HTTP Client Matters

The HTTP client is often the first place where integration issues appear. A typo in a header name, a wrong content-type, or a misread response field can break the entire feature. Unit tests for the client catch these problems early, without needing a live server. They also document the expected contract between your app and the API, making future changes safer. In TypeScript, the type system helps, but it doesn't guarantee that the runtime data matches the declared types—that's what tests are for.

What Exactly to Test in Your Client

Here's a checklist of the core behaviors to cover:

  • Request URL and method: Ensure the client calls the correct endpoint with the right HTTP verb (GET, POST, etc.).
  • Headers: Verify authentication tokens, content-type, accept headers, and any custom headers are set as expected.
  • Request body: Check that the payload is serialized correctly (JSON, form data, etc.) and matches the API spec.
  • Query parameters: Confirm that params are encoded properly and included in the URL.
  • Response parsing: Test that a successful response is transformed into the expected TypeScript type (e.g., a User object).
  • Error handling: Verify that HTTP errors (4xx, 5xx) throw the right exceptions or return a structured error object.
  • Timeout and cancellation: Ensure the client aborts the request when a timeout occurs or when the caller cancels via an AbortController.
  • Retries: If you have retry logic, test that it retries on specific status codes (e.g., 429, 503) and respects the retry count.

How to Structure Tests for an HTTP Client

The most common approach is to mock the underlying fetch or axios instance. This isolates your client code from the network, making tests fast and deterministic. For example, with Jest and fetch-mock, you can set up a mock response and assert that your client calls fetch with the expected arguments. Here's a minimal pattern:

import { fetchMock } from 'jest-fetch-mock';

fetchMock.mockResponseOnce(JSON.stringify({ id: 1, name: 'Alice' }));

const result = await getUser(1);

expect(fetchMock).toHaveBeenCalledWith('/users/1', { method: 'GET' });
expect(result).toEqual({ id: 1, name: 'Alice' });

For axios, you'd mock the axios.get method directly. The key is to mock at the boundary—the network call—so your client's logic (URL building, header injection, response mapping) is what's being tested.

Common Pitfalls and Misconceptions

One common mistake is testing the mock itself rather than your client. If you mock fetch to always return a specific response, you're not verifying that your client passes the correct parameters. Always assert on the arguments passed to the mock. Another pitfall is forgetting to test error paths. Many developers only test the happy path, leaving error handling untested. Also, beware of testing implementation details—like the exact order of headers—which makes tests brittle. Instead, test the behavior that matters: the request sent and the result returned.

Choosing the Right Testing Tools

For TypeScript, the standard stack is Jest or Vitest as the test runner, combined with a mocking library. For fetch-based clients, jest-fetch-mock or msw (Mock Service Worker) are popular. MSW is particularly useful because it intercepts real network requests at the service worker level, allowing you to test more realistic scenarios without a live server. For axios, you can use axios-mock-adapter or simply mock the module. If you're using a library like React Query or SWR, you might want to test the hooks that wrap your client, but the underlying client should still be tested in isolation.

Comparing Mocking Approaches: MSW vs. Simple Mocks

Simple mocks (like jest-fetch-mock) are easy to set up and fast, but they require you to manually simulate the fetch API. MSW, on the other hand, lets you define handlers that match URLs and return responses, which feels closer to a real server. It also works in Node.js and the browser, making it great for integration tests. The trade-off is complexity: MSW requires a bit more configuration and may be overkill for a simple client. For most projects, starting with simple mocks is fine, and you can switch to MSW when you need to test more complex interactions (e.g., multiple requests, retries).

Costs and Maintenance of Testing

Writing tests takes time, and HTTP client tests are no exception. However, the cost is usually low because the tests are small and focused. The maintenance burden comes when you change the API contract—then you must update both the client and the tests. To minimize this, keep your client thin: put all request logic in one place, and avoid scattering fetch calls across your codebase. Also, consider using a schema validator (like Zod) to parse responses, which reduces the need for extensive response-shape tests.

Safety and Security Considerations

When testing an HTTP client, never include real credentials or tokens in your test code. Use environment variables or mock values. Also, be careful with retry logic: in tests, ensure that retries don't cause infinite loops. If your client handles sensitive data, test that it doesn't log the full response body. Finally, if you're testing timeout behavior, use fake timers to avoid actually waiting the full timeout duration.

Frequently Asked Questions

Should I test the HTTP client against a real server?

Unit tests with mocked network are faster and more reliable. Integration tests against a real server are valuable but should be separate and run less frequently (e.g., in CI on a staging environment).

How do I test that a request is aborted on timeout?

Use a fake timer (e.g., jest.useFakeTimers()) and mock the fetch implementation to return a promise that rejects when the abort signal fires. Then assert that the promise rejects with an AbortError.

What's the best way to test retry logic?

Mock the fetch call to fail on the first two attempts and succeed on the third. Then assert that the client returns the success result and that fetch was called three times.

Can I test the HTTP client without mocking the network?

Yes, you can use a local server (like Express) in your test setup, but this is slower and more complex. It's usually reserved for integration tests.

How do I test that headers are set correctly?

After calling your client, inspect the mock's last call arguments. For fetch, the second argument contains the headers object. Assert that the headers include the expected key-value pairs.

Do I need to test every endpoint?

No, focus on the endpoints that have complex logic (e.g., authentication, file upload, error handling). Simple GET requests with no parameters may not need a dedicated test if they're covered by a generic test.