如何使用redux-axios-middleware测试Redux异步操作

时间:2019-06-18 08:38:13

标签: reactjs redux react-redux jestjs redux-thunk

我的Redux存储配置有redux-thunk和redux-axios-middleware,用于通过axios HTTP客户端获取数据。

我有一个动作可以很好地在开发中工作,但是我无法通过开玩笑的​​方式对其进行测试。这是动作:

export const subscribeTrial = trialingDuration => dispatch => {
  const message = `You're now Premium✨ for ${trialingDuration} days!`;

  return dispatch({
    type: SUBSCRIBE_TRIAL,
    payload: {
      request: {
        method: 'post',
        url: '/subscriptions/trial',
      },
    },
  }).then(({ type }) => {
    if (type === SUBSCRIBE_TRIAL_SUCCESS) {
      dispatch(
        showHeadMessage(message, { type: 'info', discardTimeout: 5000 }),
      );
    }
  });
};

这是我当前的测试失败:

import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';

const mockStore = configureStore([thunk]);
const store = mockStore();

beforeEach(() => {
  store.clearActions();
});

it('can start trial', () => {
  const expectedAction = {
    type: SUBSCRIBE_TRIAL,
    payload: {
      request: {
        method: 'post',
        url: '/subscriptions/trial',
      },
    },
  };

  store.dispatch(subscribeTrial());

  expect(store.getActions()).toEqual([expectedAction]);
});

玩笑不断指向.then()并引发以下错误:

TypeError: dispatch(...).then is not a function

我做错了什么?无法解决。

1 个答案:

答案 0 :(得分:0)

基于@YuryTarabanko的评论:

  

将实际发出请求的中间件添加到模拟商店中

我通过将axios客户端和中间件添加到商店来修复测试:

import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import { multiClientMiddleware } from 'redux-axios-middleware';

import axiosClients from '../../services/http_clients';

const middlewares = [thunk, multiClientMiddleware(axiosClients)];
const mockStore = configureStore(middlewares);

it('can start trial', () => {
  const store = mockStore({
    user: { email: 'user@example.com', authenticationToken: '123456' },
  });

  const expectedAction = {
    type: SUBSCRIBE_TRIAL,
    payload: {
      request: {
        method: 'post',
        url: '/subscriptions/trial',
      },
    },
  };

  store.dispatch(subscribeTrial());
  expect(store.getActions()).toEqual([expectedAction]);
});