Redux & Redux Toolkit Course
Redux & Redux Toolkit
/
Advanced

Testing Async Thunks

Definition

Writing tests for asynchronous logic, requiring you to mock the Redux store, mock the API responses, and verify that the correct sequence of actions (`pending`, `fulfilled`) were dispatched.

Explain Like I'm New

Testing API calls is hard because you don't want your test suite to ACTUALLY hit your production database. You have to 'Mock' (fake) the `fetch` function so it instantly returns fake data. Then, you track the Thunk to make sure it dispatched the `fulfilled` action with that fake data.

Real World Example

Using the `redux-mock-store` library or standard `configureStore` in a test file to intercept API calls.

Common Use Cases

  • •Testing API integration logic

Interactive Example

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { fetchUser } from './userActions';

const mockStore = configureMockStore([thunk]);

it('creates FETCH_SUCCESS when fetching user has been done', async () => {
  // 1. Fake the global fetch API to return a fake user
  global.fetch = jest.fn(() =>
    Promise.resolve({
      json: () => Promise.resolve({ name: 'John' }),
    })
  );

  // 2. Create a fake Redux store
  const store = mockStore({ users: [] });

  // 3. Dispatch the Thunk
  await store.dispatch(fetchUser());

  // 4. Verify the exact sequence of actions that were fired!
  const actions = store.getActions();
  expect(actions[0].type).toEqual('users/fetch/pending');
  expect(actions[1].type).toEqual('users/fetch/fulfilled');
  expect(actions[1].payload).toEqual({ name: 'John' });
});

Interview Questions

basic

  • Should your unit tests make real network requests to your live database?

intermediate

  • What library is highly recommended for mocking network requests in modern Redux tests?

Flash Cards

Question

Real network requests?

Click to reveal answer
Answer

NEVER. Unit tests must be fast and deterministic. Network requests are slow and can fail if the wifi drops. You must 'mock' (fake) the responses.

Question

Recommended library?

Click to reveal answer
Answer

Mock Service Worker (MSW). It intercepts requests at the network level, providing incredibly realistic fake responses for your Thunks and RTK Query endpoints.