Skip to content

Fix MSW Handler Not Caught – Request Not Intercepted

DodaTech Updated 2026-06-24 3 min read

In this tutorial, you'll learn about Fix MSW Handler Not Caught. We cover key concepts, practical examples, and best practices.

You set up MSW handlers, start the server, and make a request in your test — but it hits the real API. The server logs "[MSW] Warning: captured a request without a matching request handler". The handler exists but isn't matching.

Wrong ❌

// mocks/handlers.js
import { http, HttpResponse } from 'msw';

export const handlers = [
  http.get('/api/users', () => {                             // ❌ relative URL
    return HttpResponse.json([{ id: 1, name: 'Alice' }]);
  }),
];
// user.test.js
import { setupServer } from 'msw/node';
import { handlers } from './mocks/handlers';

const server = setupServer(...handlers);
beforeAll(() => server.listen());
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('fetch users', async () => {
  const res = await fetch('http://localhost:3001/api/users');   // absolute URL
  // MSW logs: captured a request without a matching request handler
});

The handler has a relative URL /api/users, but the fetch uses an absolute URL http://localhost:3001/api/users. MSW doesn't match them.

// mocks/handlers.js
import { http, HttpResponse } from 'msw';

export const handlers = [
  // ✅ Use absolute URL or wildcard
  http.get('http://localhost:3001/api/users', () => {
    return HttpResponse.json([{ id: 1, name: 'Alice' }]);
  }),

  // Or use a wildcard to match any origin:
  http.get('*/api/users', () => {
    return HttpResponse.json([{ id: 1, name: 'Alice' }]);
  }),
];
// user.test.js
import { setupServer } from 'msw/node';
import { handlers } from './mocks/handlers';

const server = setupServer(...handlers);

beforeAll(() => server.listen({ onUnhandledRequest: 'warn' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('fetch users', async () => {
  const res = await fetch('http://localhost:3001/api/users');
  const data = await res.json();

  expect(data).toEqual([{ id: 1, name: 'Alice' }]);     // ✅
});

For GraphQL:

import { graphql, HttpResponse } from 'msw';

export const handlers = [
  graphql.query('GetUser', ({ variables }) => {
    const { id } = variables;
    return HttpResponse.json({
      data: { user: { id, name: 'Alice' } },
    });
  }),
];

Debug unhandled requests:

const server = setupServer(...handlers);
server.listen({
  onUnhandledRequest: 'bypass',    // default — let it pass through
  // 'warn' — log a warning
  // 'error' — throw an error on unhandled
});

Set to 'error' in CI to catch missing handlers:

if (process.env.CI) {
  server.listen({ onUnhandledRequest: 'error' });
}

Add a fallback handler:

server.use(
  http.all('*', ({ request }) => {
    console.warn('Unhandled:', request.method, request.url);
    return HttpResponse.json({ error: 'Not mocked' }, { status: 501 });
  })
);

Root Cause

MSW matches handlers by method + URL. If the URL scheme, host, port, or path differs between the handler and the actual request, it won't match. Relative URLs in handlers only match requests made to the same origin as the test page.

Prevention

  • Use * wildcard in the URL: http.get('*/api/users', ...) matches any origin.
  • Use absolute URLs matching the test's base URL.
  • Enable onUnhandledRequest: 'warn' during development to see missed requests.
  • Use server.printHandlers() to list all registered handlers.

Common Mistakes with handler not caught

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world MSW code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

**Q: Can I use MSW with `page.route()` in Playwright?**

A: MSW is for Node/unit tests and Storybook. For Playwright E2E, use page.route().

**Q: Why does my POST handler not match?**

A: Check the method: http.post('*/api/users', ...) vs http.get(...).

**Q: How do I reset handlers between tests?**

A: afterEach(() => server.resetHandlers()) clears runtime handlers but keeps the initial ones.

**Q: Can I conditionally return different responses?**

A: Yes — use server.use() within a test to override handlers temporarily.


MSW setup is covered in the DodaTech API Mocking course.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro