Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 41 ยท Testing and Tooling

Testing React Components with Redux

Test connected React components with a real Redux store: a renderWithProviders helper, preloaded state, user events, and mocking the network with MSW for RTK Query apps.

A component that reads from Redux can be tested in two ways. You can mock useSelector and useDispatch, or you can render the component inside a real store and interact with it like a user. The second is what the Redux and React Testing Library teams recommend: it tests what the user sees, and it keeps working when you refactor reducers, selectors or the component's internals.

React Testing Library, Vitest and MSW are not available in the editors here, so the real test code is read-only. A runnable stand-in at the end shows the central idea (a fresh store plus a "render" function) without a DOM library.

The renderWithProviders helper

Every test needs the Provider and a store. Put that into one helper so tests stay short. It creates a new store per call, optionally from preloadedState, and returns it so tests can inspect it.

JSX
// Real React-Redux + Testing Library code (read-only): test-utils.jsx
import { render } from '@testing-library/react';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import { rootReducer } from './store';

export function renderWithProviders(
  ui,
  { preloadedState, store = configureStore({ reducer: rootReducer, preloadedState }), ...options } = {},
) {
  function Wrapper({ children }) {
    return <Provider store={store}>{children}</Provider>;
  }
  return { store, ...render(ui, { wrapper: Wrapper, ...options }) };
}

Using rootReducer (instead of importing the app's store) lets each test have its own isolated state. If your app also uses a router, add MemoryRouter to the wrapper.

A component test

JSX
// Real code (read-only)
import { screen } from '@testing-library/react';
import userEvent from '@testing-library/user-event';
import { renderWithProviders } from './test-utils';
import { Cart } from './Cart';

test('shows the total from the store', () => {
  renderWithProviders(<Cart />, {
    preloadedState: { cart: { items: [{ id: 1, name: 'Tea', price: 5, qty: 2 }] } },
  });
  expect(screen.getByText('Total: $10.00')).toBeInTheDocument();
});

test('removing an item updates the total', async () => {
  const user = userEvent.setup();
  const { store } = renderWithProviders(<Cart />, {
    preloadedState: { cart: { items: [{ id: 1, name: 'Tea', price: 5, qty: 2 }] } },
  });
  await user.click(screen.getByRole('button', { name: /remove tea/i }));
  expect(screen.getByText('Your cart is empty')).toBeInTheDocument();
  expect(store.getState().cart.items).toHaveLength(0);   // optional: confirm the store changed
});

Guidelines:

  • Query by role and text (getByRole, getByText, getByLabelText), as a user perceives the page. Avoid test ids unless nothing else works.
  • Start from preloadedState instead of replaying many clicks to reach a scenario.
  • Use await with userEvent and findBy*/waitFor for anything async.
  • Assert on the UI first, on the store second. The UI is the contract.
  • Only set up the slices the component needs; a partial preloadedState works if the reducers supply defaults for the rest (use combineReducers or configureStore with a reducer object for this).

Mocking the network with MSW

Components that load data with thunks or RTK Query call fetch. Mock it at the network boundary with Mock Service Worker (MSW) so the real thunk, the real cache and the real store all run:

JSX
// Real code (read-only): MSW 2
import { http, HttpResponse } from 'msw';
import { setupServer } from 'msw/node';

const server = setupServer(
  http.get('/api/posts', () => HttpResponse.json([{ id: 1, title: 'Hello' }])),
);
beforeAll(() => server.listen({ onUnhandledRequest: 'error' }));
afterEach(() => server.resetHandlers());
afterAll(() => server.close());

test('lists posts from the API', async () => {
  renderWithProviders(<PostList />);
  expect(screen.getByText(/loading/i)).toBeInTheDocument();
  expect(await screen.findByText('Hello')).toBeInTheDocument();
});

test('shows an error message when the server fails', async () => {
  server.use(http.get('/api/posts', () => new HttpResponse(null, { status: 500 })));
  renderWithProviders(<PostList />);
  expect(await screen.findByText(/something went wrong/i)).toBeInTheDocument();
});

Two RTK Query specifics:

  1. Use a new store (and therefore a new cache) per test. If tests share the API slice's state they will see each other's cached data. Alternatively dispatch api.util.resetApiState() in afterEach.
  2. Relative URLs need a base in Node. fetchBaseQuery({ baseUrl: '/api' }) fails under Node's fetch; set baseUrl to an absolute URL such as http://localhost/api in the test environment, or configure it from an environment variable.

What not to do

  • Do not mock react-redux hooks (useSelector: jest.fn()): the test then proves nothing about your selectors or state.
  • Do not import the singleton store in tests: it keeps state between tests.
  • Do not assert on implementation details such as the dispatched action list when the visible result tells the same story.
  • Do not use act() warnings as noise to silence; they often mean a missing await or findBy.

A runnable stand-in

This example has no DOM library. It models a "component" as a function from state to a string, and renderWithStore creates a fresh store per test and re-renders on every change. It demonstrates why per-test stores and preloadedState matter.

JS Fresh store per test with preloaded state

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Because each test owns its store, test 3 starts from the preloaded cart even though test 2 emptied one. A shared singleton store would have failed test 3, depending on the order in which tests run.

End-to-end tests

Unit and integration tests cannot tell you that the real browser, real server and real store work together. Keep a small number of Playwright or Cypress tests for the critical journeys (log in, add to cart, pay), and keep the rest as fast store-level and component tests. Details of tooling are in DevTools and debugging.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does renderWithProviders create a new store for each call?

    Isolated tests do not depend on each other's order.
  2. 2. What is a reason to prefer a real store over mocking useSelector?

    Mocked hooks test the mock, not your Redux logic.
  3. 3. Where should network mocking happen for tests that use RTK Query?

    That way the real cache, middleware and thunks run.
  4. 4. What is the best way to reach a complex scenario in a component test?

    preloadedState starts the store in the exact state you need.

Summary

  • Render components inside a real Provider with a fresh store per test.
  • Use preloadedState for setup, query by role and text, and assert on visible output.
  • Mock the network with MSW and reset the RTK Query cache between tests.
  • Do not mock react-redux hooks or share a singleton store.
  • Keep a few end-to-end tests for critical journeys.

Next: Redux DevTools and debugging