Course contentsShow
← React
Lesson 2087 of 2,39646. Testing React with RTLFree lesson

Defining Request Handlers with http.get

Create mock endpoints using http.get('/path', resolver) to return JSON responses for GET requests.

Defining Request Handlers with http.get

What you'll learn: How to create mock API endpoints that respond to GET requests during testing using MSW's http.get handler.

The Core Idea

Think of http.get() as defining a pretend API endpoint that lives inside your test environment. When your React component tries to fetch data from a URL, MSW intercepts that request and returns whatever response you've configured—no real server needed.

The pattern is simple: http.get('/path', resolver). The first argument is the URL path you want to intercept, and the second is a resolver function that returns the mock response.

Creating a Handler

import { http, HttpResponse } from 'msw';

const handlers = [
  http.get('/api/users', () => {
    return HttpResponse.json([
      { id: 1, name: 'Alice' },
      { id: 2, name: 'Bob' }
    ]);
  })
];

When your component makes a GET request to /api/users, MSW catches it and immediately responds with that JSON array. Your component never knows it's not talking to a real API.

Why This Matters

This approach lets you test how your component handles successful data fetching without spinning up a server or making real network calls. The resolver function runs synchronously (though MSW handles it asynchronously under the hood), giving you full control over what data your component receives.

You can define multiple handlers for different endpoints, and MSW will match requests by URL pattern. The resolver has access to request details if you need them, but for basic cases, returning HttpResponse.json() with your mock data is all you need.

Key Takeaway: http.get('/path', resolver) creates a mock endpoint that intercepts GET requests and returns JSON responses, allowing you to test data fetching without real network calls.