Skip to content
Advertisement

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 UserService.getUser();
      dispatch(userLoading());
    } catch (error) {
      dispatch(userError(error));
    } finally {
      dispatch(userSuccess(response));
    }
  };
};

With the following unit test I was abale to hit the “dispatch(userRequest());”

describe('user thunk', () => {
    it('dispatches a userRequest', async () => {
      const dispatch = jest.fn();

      await loadUsers()(dispatch);
      expect(dispatch).toHaveBeenCalledWith(userRequest());
    });
  });

However I couldn’t figure out how to test lines and below response= await UserService.getUser();. Even though the function is not complex and I won’t have much value for writing complex test, I need it for my pipeline to build.

Any help will be appreciated.

Thanks in advance.

UPDATE-> User Service

import axios from 'axios';

const USERS_ENDPOINT = '/user';

export const getUser= async () => {
  const response = await axios.get(PRODUCTS_ENDPOINT, {});
  return response.data;
};

export default getUser;

Advertisement

Answer

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

JavaScript
User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement