Skip to content Skip to sidebar Skip to footer

Unit Testing React Redux Thunk Dispatches With Jest And React Testing Library For "v: 16.13.1",

I have following function. const loadUsers= () => { return async (dispatch) => { dispatch(userRequest()); let response= null try { response= await UserSe

Solution 1:

After days of research, I ended up testing the logic the following way.

import thunk from 'redux-thunk';
import configureStore from 'redux-mock-store';
import * as reactRedux from 'react-redux';

import axios from 'axios';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);

describe('load user thunk', () => {
it('dispatches load user and error on call when API is not mocked', async () => {
  const store = mockStore({});
  const requestDispatch= userRequest();
  const errorDispatch= userError("Mock Message");

  await store.dispatch(await loadUsers());
  const actionsResulted = store.getActions();
  const expectedActions = [
    requestDispatch,
    errorDispatch,
  ];
  expect(actionsResulted.length).toEqual(expectedActions.length);
  expect(actionsResulted[0].type).toEqual(expectedActions[0].type);
  expect(actionsResulted[1].type).toEqual(expectedActions[1].type);
}); 

it('dispatches load user and success on call when API is mocked', async () => {
  const store = mockStore({});
  const requestDispatch= userRequest();
  const successDispatch= userSuccess("Mock Data");
  jest
  .spyOn(axios, 'get')
  .mockResolvedValue({ status: 200, data: "Mock Data"});

  await store.dispatch(await loadUsers());
  const actionsResulted = store.getActions();
  const expectedActions = [
    requestDispatch,
    successDispatch,
  ];
  expect(actionsResulted.length).toEqual(expectedActions.length);
  expect(actionsResulted[0].type).toEqual(expectedActions[0].type);
  expect(actionsResulted[1].type).toEqual(expectedActions[1].type);

 });

Post a Comment for "Unit Testing React Redux Thunk Dispatches With Jest And React Testing Library For "v: 16.13.1","