Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Advanced

Testing RTK Query

Definition

Techniques for testing the React hooks generated by RTK Query, ensuring that components render loading spinners, handle fake data from MSW, and display errors correctly.

Explain Like I'm New

Instead of testing the Redux store in isolation, you wrap a React component in a `<Provider>`, mock the network with Mock Service Worker (MSW), and use React Testing Library to literally check if the Loading Spinner appears, and then disappears when the fake data arrives.

Real World Example

Testing that a `<PokemonCard />` component displays 'Loading...', then a split second later displays 'Pikachu'.

Common Use Cases

  • •Component integration testing

Interactive Example

import { render, screen } from '@testing-library/react';
import { Provider } from 'react-redux';
import { store } from './store';
import { PokemonCard } from './PokemonCard';

// Assuming MSW is configured globally to intercept the /pokemon API...

it('renders loading state, then data', async () => {
  render(
    <Provider store={store}>
      <PokemonCard name="pikachu" />
    </Provider>
  );

  // 1. Immediately check for the loading state
  expect(screen.getByText(/loading/i)).toBeInTheDocument();

  // 2. Wait for RTK Query to resolve the mock data, and check the UI again
  const pikachuText = await screen.findByText(/Pikachu/i);
  expect(pikachuText).toBeInTheDocument();
});

Interview Questions

basic

  • What does MSW stand for?

intermediate

  • Why do you need to wrap your component in a `<Provider>` during testing?

Flash Cards

Question

MSW?

Click to reveal answer
Answer

Mock Service Worker.

Question

Why Provider?

Click to reveal answer
Answer

Because the `useGetPokemonQuery()` hook inside the component relies on React Context. If it is not wrapped in a Redux `<Provider>` attached to a test store, the hook will crash immediately.