How to Mock SWR in React

Testing React components that use the SWR library for data fetching requires a reliable way to mock network requests and hook return states. This article demonstrates how to mock the SWR library in React using two primary approaches: utilizing the officially recommended <SWRConfig> provider to seed cache data, and using Jest to mock the useSWR hook directly for isolated unit tests.

The cleanest and most robust way to mock SWR is by wrapping your test component in the <SWRConfig> component. This approach avoids global Jest mocks, ensures cache isolation between tests, and allows you to inject mock data directly into the SWR provider.

To reset the cache between tests, pass an empty Map to the provider option, and use the fallback option to supply your mock data.

import React from 'react';
import { render, screen } from '@testing-library/react';
import { SWRConfig } from 'swr';
import { UserProfile } from './UserProfile';

describe('UserProfile Component', () => {
  it('renders user data from SWR cache', async () => {
    const mockData = { name: 'John Doe', email: 'john@example.com' };

    render(
      <SWRConfig value={{ 
        provider: () => new Map(), 
        fallback: { '/api/user': mockData },
        dedupingInterval: 0 
      }}>
        <UserProfile />
      </SWRConfig>
    );

    expect(await screen.findByText('John Doe')).toBeInTheDocument();
  });
});

Method 2: Mocking useSWR with Jest

If you prefer to control the exact return values of the hook (such as testing explicit loading, error, and success states), you can mock the swr module directly using Jest.

1. Mock the module at the top of your test file:

import useSWR from 'swr';

jest.mock('swr');

2. Define the mock return values in your tests:

import React from 'react';
import { render, screen } from '@testing-library/react';
import { UserProfile } from './UserProfile';
import useSWR from 'swr';

const mockUseSWR = useSWR as jest.Mock;

describe('UserProfile Component with Jest Mocks', () => {
  beforeEach(() => {
    mockUseSWR.mockReset();
  });

  it('renders loading state', () => {
    mockUseSWR.mockReturnValue({
      data: undefined,
      error: undefined,
      isLoading: true,
    });

    render(<UserProfile />);
    expect(screen.getByText('Loading...')).toBeInTheDocument();
  });

  it('renders data state', () => {
    mockUseSWR.mockReturnValue({
      data: { name: 'Jane Doe' },
      error: undefined,
      isLoading: false,
    });

    render(<UserProfile />);
    expect(screen.getByText('Jane Doe')).toBeInTheDocument();
  });

  it('renders error state', () => {
    mockUseSWR.mockReturnValue({
      data: undefined,
      error: new Error('Failed to fetch'),
      isLoading: false,
    });

    render(<UserProfile />);
    expect(screen.getByText('Error loading profile')).toBeInTheDocument();
  });
});