如何测试Redux-Thunk使用Unit Test Jest的动作?

时间:2017-07-13 13:14:13

标签: unit-testing redux jestjs redux-thunk

我是 Redux-thunk p>

以下是代码:

export const functionA = (a,b) => (dispatch) =>{
    dispatch ({type: CONSTANT_A, payload: a});
    dispatch ({type: CONSTANT_B, payload: b});
} 

如何使用 Unit-Test Jest 测试功能?任何人都可以帮助我^^。提前感谢:)

3 个答案:

答案 0 :(得分:6)

您在Redux文档中有一个示例:http://redux.js.org/docs/recipes/WritingTests.html#async-action-creators

import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)

describe('async actions', () => {

  it('should dispatch actions of ConstantA and ConstantB', () => {
    const expectedActions = [
      {type: CONSTANT_A, payload: 'a'},
      {type: CONSTANT_B, payload: 'b'} 
    ]

    const store = mockStore({ yourInitialState })
    store.dispatch(actions.functionA('a', 'b'))

    expect(store.getActions()).toEqual(expectedActions)
  })
})

答案 1 :(得分:1)

此外,为了更加方便,您可以使用以下模块:https://www.npmjs.com/package/redux-thunk-tester

例如:

import React from 'react';
import {createStore, applyMiddleware, combineReducers} from 'redux';
import {reducer} from './example';
import ReduxThunkTester from 'redux-thunk-tester';
import thunk from 'redux-thunk';

const request = (ms) => new Promise((resolve) => {
  setTimeout(() => resolve('success response'), ms);
});

const resultRequestAction = (value) => ({ type: SOME_BACKEND_REQUEST, payload: value });
const toggleLoadingAction = (value) => ({ type: TOGGLE_LOADING, payload: value });

const asyncThunkWithRequest = () => async (dispatch) => {
  try {
    dispatch(toggleLoadingAction(true));
    const result = await request(200);
    dispatch(resultRequestAction(result));
  } finally {
    dispatch(toggleLoadingAction(false));
  }
};

const createMockStore = () => {
  const reduxThunkTester = new ReduxThunkTester();

  const store = createStore(
    combineReducers({exampleSimple: reducer}),
    applyMiddleware(
      reduxThunkTester.createReduxThunkHistoryMiddleware(),
      thunk
    ),
  );

  return {reduxThunkTester, store};
};

describe('Simple example.', () => {
  test('Success request.', async () => {
    const {store, reduxThunkTester: {getActionHistoryAsync, getActionHistoryStringifyAsync}} = createMockStore();

    store.dispatch(asyncThunkWithRequest());

    const actionHistory = await getActionHistoryAsync(); // need to wait async thunk (all inner dispatch)

    expect(actionHistory).toEqual([
      {type: 'TOGGLE_LOADING', payload: true},
      {type: 'SOME_BACKEND_REQUEST', payload: 'success response'},
      {type: 'TOGGLE_LOADING', payload: false},
    ]);

    expect(store.getState().exampleSimple).toEqual({
      loading: false,
      result: 'success response'
    });

    console.log(await getActionHistoryStringifyAsync({withColor: true}));
  });
});

答案 2 :(得分:0)

为了避免出现异步问题,我建议您编写如下代码:

return store
  .dispatch(actionCreators.login({}))
  .then(() => expect(store.getActions()).toEqual(expectedActions));