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?