Unit testing jest redux thunk测试是否调度了相同模块的操作

Unit testing jest redux thunk测试是否调度了相同模块的操作,unit-testing,redux,flux,redux-thunk,jestjs,Unit Testing,Redux,Flux,Redux Thunk,Jestjs,我正在尝试为redux操作创建者编写一个测试,该创建者将分派在同一文件中定义的另一个操作。这很难解释,下面是一个例子: // actions/timer.js export const onClickButton = () => { return dispatch => { // ... do something dispatch(someAction); dispatch(onTimerStart()); // This is the action c

我正在尝试为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,我想确保调用
onClickButton
时调度
onTimerStart
操作。(在我的实际代码中,这些操作创建者使用一些参数,并基于这些参数,
onTimerStart
应该或不应该被调度)

我似乎不知道如何模拟
onTimerStart
,所以我可以测试它是否被调用

  • 您可以使用
    jest.fn()
    为分派创建一个模拟

  • 然后,调用action creator一次,以获取“thunk”(返回的函数,将dispatch作为参数)

  • 这样,以模拟分派作为参数调用返回的函数

  • 您可以使用dispatch.mock.calls查看要分派的调用

  • (1)模拟功能

    const dispatch = jest.fn();
    
    (2)(3)发出砰的一声并称之为

    const thunk = onClickButton();
    thunk(dispatch);
    
    (4)检查要调度的呼叫

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

    您可以使用“”并断言预期的操作已被调度,而不是模拟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);
        });
    
    });
    
    使用这个示例,您只需要添加您提到的参数,并从正确的位置导入ActionCreator、ActionType和initialState


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

    你好,尼克,谢谢您的示例。如果有一个调度,您的示例就可以运行。但是,当存在多个调度时,断言总是采用最后一个调度,因此我试图找出如何在相同的操作中测试多个调度。我无法在注释中清晰地发布代码,但给您一个来自原始问题的示例,第二个操作“onTimerStart”是一个单独的调度(有效),而“onClickButton”有两个调度,jest只捕获第二个。@AndriyKulak,听起来您好像在尝试测试异步操作。查看redux文档了解如何做到这一点-Hi@Bram:Iam也有类似的问题,您是否找到了解决问题的方法?如果是,请分享结果