jest redux-thunk测试是否调度相同模块的动作

时间:2017-02-01 21:43:00

标签: unit-testing redux flux redux-thunk jest

我正在尝试为redux动作创建者编写一个测试,该动作创建者调度在同一文件中定义的另一个动作。这很难解释,所以这是一个例子:

// actions/timer.js

export const onClickButton = () => {
  return dispatch => {
    // ... do something
    dispatch(someAction);
    dispatch(onTimerStart()); // This is the action creator stated below
  };
};

export const onTimerStart = () => {
  return dispatch => {
    // ... do something
    dispatch(someAction);
  };
};

我正在使用jest,我想确保在调用onTimerStart时调度onClickButton操作。 (在我的实际代码中,这些动作创建者会采用一些参数,并根据这些参数,onTimerStart应该或不应该被派遣)

我似乎无法弄清楚如何模仿onTimerStart所以我可以测试它是否被调用。

2 个答案:

答案 0 :(得分:1)

您可以使用“redux-mock-store”而不是模拟onTimerStart(),并声明已分派了您预期的操作。

这是一个粗略的例子。

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as timerActions from './actions/timerActions';
import * as types from './constants/actionTypes';
import { InitialAppState } from './reducers/initialState';

const createMockStore = configureMockStore([thunk]);

describe('timerActions', () => {

    it('successful call should dispatch someAction', () => {

        // Arrange.
        const expectedActions = [
            { type: types.someAction},
        ];

        const store = createMockStore(InitialAppState);

        // Act.
        store.dispatch(actions.onClickButton());

        // Assert.
        const dispatchedActions = store.getActions();
        expect(dispatchedActions).toEqual(expectedActions);
    });

});

使用此示例,您只需要添加您提到的参数,并从正确的位置导入actionCreators,actionTypes和initialState。

请注意,此示例是用typescript编写的。

答案 1 :(得分:0)

  1. 您可以使用jest.fn()为调度创建模拟。

  2. 然后,调用动作创建者一次以获取“thunk”(将调度作为参数的返回函数)。

  3. 使用它,以模拟调度作为参数调用返回的函数。

  4. 您可以使用dispatch.mock.calls查看调度调用。

  5. (1)模拟功能

    const dispatch = jest.fn();
    

    (2)(3)获取thunk并将其调用

    const thunk = onClickButton();
    thunk(dispatch);
    

    (4)检查调度电话

    // indices mean: [the second call] [the first argument of that call]
    dispatch.mock.calls[1][0]