使用Jest对React Redux中的多个调度操作进行单元测试

时间:2017-07-10 03:09:26

标签: unit-testing redux jestjs redux-thunk

我有一种感觉,我错过了一些简单的事情,但我有一个动作,如果满足条件,就会发出两个动作。

动作

Jest.fn()

然后我尝试测试load()并使用mock.calls.length进行模拟,但是当我在发送changeDateRange()后记录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 ??
  })
})

测试

tf.train.batch

有什么想法吗?

1 个答案:

答案 0 :(得分: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 本身需要成为模拟函数。