Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing multiple dispatched actions in React Redux with Jest

I have a feeling i'm missing something simple but I have an action that dispatches two actions if a condition is met.

Action

export function changeDateRange({ startDate, endDate }) {
  return function reload(dispatch, getState) {
    if (!getState().navigation.focused) {
      // If our datepicker has closed, reload the data on the page
      dispatch(load());
    }
    dispatch({
      type: types.CHANGE_DATE_RANGE,
      startDate,
      endDate
    });
  };
}

Then I am trying to test load() and have mocked it with a Jest.fn() but when I log mock.calls.length after dispatching changeDateRange() It equals 0?

Setup

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
global.mockStore = configureMockStore([thunk]);

Test:

import * as types from '../actionTypes';
import * as changeDateRange from './changeDateRange';
import { load } from '../reporting';

jest.mock('../reporting', () => ({
  load: () => jest.fn()
}));

describe('Reducer: changeDateRange Reducer', () => {
  it('should change date range', () => {
    const store = mockStore({
      startDate: '',
      endDate: '',
      navigation: {
        focused: false
      }
    });
    const dateRange = {
      startDate: 'yes',
      endDate: 'yes'
    };
    store.dispatch(changeDateRange(dateRange));
    expect(store.getActions()).toEqual([
      Object.assign(
        {
          type: types.CHANGE_DATE_RANGE
        },
        dateRange
      )
    ]);
    console.log(load().mock.calls.length); // === 0 ??
  });
});

Any ideas?

like image 677
csilk Avatar asked Jul 10 '17 03:07

csilk


1 Answers

Weird such an old question doesn't have an answer. Because it has 8 upvotes I'll answer it for the next person who finds it. The OP has mocked load incorrectly. It should look like this:

jest.mock('../reporting', () => ({
  load: jest.fn() //not () => jest.fn()
}));

And then down in the code they could do this:

console.log(load.mock.calls.length); // not load().mock.calls.length

Every time load was called it returned a new mock function. When in fact load itself needed to be the mock function.

like image 147
Adam Avatar answered Nov 15 '22 08:11

Adam