8

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?

1
  • Are you sure your changeDateRange() get called? Probably, your action module imports it different way. Commented Aug 19, 2019 at 15:32

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.