Programming guides, explanations and reader checklists on whilenetworking.com

Writing Integration Tests for API Endpoints: Mocking External Services with MSW and Jest

Integration tests bridge the gap between unit tests and end-to-end (E2E) suites. While unit tests verify individual functions in isolation, integration tests…

Integration tests bridge the gap between unit tests and end-to-end (E2E) suites. While unit tests verify individual functions in isolation, integration tests validate that components interact correctly. However, running full E2E tests against live databases, third-party payment gateways, or external APIs is often too slow, expensive, or brittle for a CI/CD pipeline. This is where mocking becomes essential.

Modern JavaScript developers frequently use MSW (Mock Service Worker) combined with Jest to simulate network traffic at the browser level. Unlike server-side mocks that intercept fetch calls within Node.js, MSW operates in the browser, allowing you to test React applications or any client-side code without modifying the actual application logic. This approach ensures your tests remain fast, deterministic, and independent of external service availability.

Why Mock External Services with MSW?

In a typical development environment, an integration test might attempt to call a real user management API like https://api.stripe.com/v1. If that service is down, rate-limited, or returns a 503 error, your test suite fails immediately. This introduces noise into the feedback loop for developers.

By using MSW, you can intercept these requests before they leave the browser. You gain complete control over the response:
* Status Codes: Force a 401 Unauthorized to test authentication flows.
* Data Payloads: Return specific JSON structures to verify how your UI renders different data states.
* Delay Simulation: Introduce artificial latency to see if your application handles timeouts gracefully.

The primary benefit is isolation. Your tests run in a sandboxed environment where the “network” behaves exactly as you define it, ensuring that failures are due to logic errors in your code, not flaky external dependencies.

Setting Up the Environment

Before writing tests, you must configure the project correctly. We will assume a standard React application setup using Vite or Create React App. The following steps outline the installation and configuration process.

  1. Install Dependencies: You need Jest for running the test runner and MSW to handle the mocking.
    bash
    npm install -D jest @mswjs/jest msw
  2. Initialize MSW in Jest: Create a file named setupTests.js (or include it in your existing setup file) to register the worker globally.
    “`javascript
    import { setupWorker } from ‘msw’

    const worker = setupWorker(
    // Define mock handlers here
    )

    export default worker
    3. **Configure Jest**: Update your `jest.config.js` or the `setupFilesAfterEnv` property in `package.json` to ensure MSW is initialized before every test run.json
    {
    “setupFilesAfterEnv”: [“/src/setupTests.js”]
    }
    “`

Defining Mock Handlers for API Endpoints

Once the worker is active, you define handlers that intercept requests matching specific criteria. These handlers return mocked responses instead of making real network calls.

Consider a scenario where your application fetches a list of products from an external catalog service. You want to mock this endpoint to return a static list of items.

import { rest } from 'msw'
import { setupWorker } from '@mswjs/jest'

const worker = setupWorker(
  rest.get('/api/products', (req, res, ctx) => {
    // Return a successful response with specific data
    return res(
      ctx.json([{ id: 1, name: 'Laptop', price: 999 }])
    )
  }),
  rest.post('/api/checkout', (req, res, ctx) => {
    // Handle POST requests, perhaps simulating a successful payment
    return res(
      ctx.json({ success: true, transactionId: 'txn_123' })
    )
  })
)

worker.start()

In this example, any GET request to /api/products will receive the mocked JSON array. Any POST to /api/checkout will receive a success payload. This allows you to test the UI’s reaction to these specific data points without hitting a real server.

Testing Error States and Edge Cases

A robust integration test suite must handle failure scenarios. Real-world APIs frequently return 401, 403, or 500 errors. MSW makes it trivial to simulate these states by returning custom status codes in your handler.

rest.get('/api/users', (req, res, ctx) => {
  // Simulate an unauthorized access error
  return res(
    ctx.status(401),
    ctx.json({ error: 'Unauthorized' })
  )
})

When writing tests, you can assert that your application correctly displays an error message or redirects the user when this response is received. This prevents production bugs where an unhandled API error causes a crash instead of a graceful degradation.

Running and Verifying Tests

With handlers defined in setupTests.js, you can now write standard Jest tests in your __tests__ directory. The MSW worker automatically starts before the test environment loads.

import { rest } from 'msw'
import { setupWorker } from '@mswjs/jest'
import userEvent from '@testing-library/user-event'
import { render, screen } from '@testing-library/react'
import App from '../App'

worker.start()

test('displays product list on load', async () => {
  const user = userEvent.setup()

  // Render the app; MSW intercepts the fetch inside the component
  render(<App />)

  // Assert that the expected data appears in the DOM
  expect(screen.getByText(/Laptop/i)).toBeInTheDocument()
})

Expected Output: The test runner executes, the mock server activates, and the assertion passes. If you remove the worker.start() call or fail to define a handler for a route, the test will fail with a “Network Error” or “Failed to fetch,” indicating that the mock is missing.

Common Mistakes and Debugging Tips

Developers often encounter specific pitfalls when adopting MSW:
* Missing CORS Headers: MSW runs in a browser context. If you try to mock a request to an origin that doesn’t match your current file origin, you might hit CORS issues if not configured correctly. Always ensure the rest.get or rest.post path matches exactly, including query parameters if necessary.
* Async Timing Issues: If your component relies on timing (e.g., setTimeout) before fetching data, ensure your mock response is immediate unless you explicitly use ctx.delay(ms) to simulate network latency.
* Global State Leakage: Remember that MSW resets between test runs in Jest. Do not rely on global variables set during one test affecting another; keep handlers isolated within the setup file.

To debug, inspect the Network tab in your browser’s DevTools while running tests. You should see requests being intercepted with the “Mocked” label rather than hitting the actual network.

Student Practice Task: Building a Mocked Login Flow

For students and junior engineers, a practical exercise solidifies understanding. Create a simple React app with a login form.
1. Set up MSW in Jest as described above.
2. Create a mock handler for POST /api/login that accepts a JSON body { username: string, password: string }.
3. Implement logic where the mock returns a success token only if the username is “admin” and password is “secret”.
4. Write a test that submits these credentials and verifies the app navigates to the dashboard.
5. Write a second test that submits wrong credentials and verifies an error message appears.

This task covers authentication flows, state management, DOM assertions, and the core value of mocking: decoupling logic from infrastructure.

Educational-use notice: This tutorial is for learning and controlled lab use only. Test carefully, use backups, and obtain authorization before making changes. Do not run unfamiliar commands on production systems. We accept no responsibility for misuse, damage, data loss, or production issues.