How can I test Action of Redux-Thunk use Unit Test Jest?

╄→гoц情女王★ 提交于 2019-12-10 16:45:21

问题


I'm new to unittesting a Action of Redux-thunk use Jest.

Here is following Code :

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

How can i test for the function use Unit-Test Jest ? Anyone can help me ^^. Thank in advance :)


回答1:


You have an example in the Redux docs: 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)
  })
})



回答2:


Also, for more more convenience, you can use this module: https://www.npmjs.com/package/redux-thunk-tester

Exmaple:

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




回答3:


I recommend you to write something like this to avoid async problems:

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


来源:https://stackoverflow.com/questions/45081717/how-can-i-test-action-of-redux-thunk-use-unit-test-jest

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!