【问题标题】:Unit testing multiple dispatched actions in React Redux with Jest使用 Jest 在 React Redux 中对多个调度的操作进行单元测试
【发布时间】:2017-12-13 16:04:40
【问题描述】:

我感觉我错过了一些简单的东西,但是如果满足条件,我有一个动作会分派两个动作。

动作

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
    });
  };
}

然后我尝试测试 load() 并用 Jest.fn() 模拟它,但是当我在调度 changeDateRange() 后登录 mock.calls.length 时它等于 0

设置

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

测试:

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 ??
  });
});

有什么想法吗?

【问题讨论】:

  • 你确定你的 changeDateRange() 被调用了吗?可能,您的操作模块以不同的方式导入它。

标签: unit-testing redux jestjs redux-thunk


【解决方案1】:

奇怪的是,这么老的问题没有答案。因为它有 8 个赞成票,所以我会为下一个找到它的人回答它。 OP 错误地模拟了负载。它应该是这样的:

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

然后在代码中他们可以这样做:

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

每次调用 load 时,它都会返回一个新的模拟函数。事实上 load 本身需要是模拟函数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-08-17
    • 2020-07-24
    • 2017-04-14
    • 1970-01-01
    • 2017-12-01
    • 2018-04-06
    • 1970-01-01
    • 2020-10-03
    相关资源
    最近更新 更多