【问题标题】:How to test Redux async action with redux-axios-middleware如何使用 redux-axios-middleware 测试 Redux 异步操作
【发布时间】:2019-10-31 20:30:16
【问题描述】:

我的 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]);
});

Jest 一直指向 .then() 并引发以下错误:

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

我做错了什么?想不通。

【问题讨论】:

  • 你在哪里/如何使用 axios?
  • 我使用 redux-axios-middleware 与 axios HTTP 客户端获取数据
  • 您需要将实际执行请求的中间件添加到模拟存储。或者您可以创建一个以某种方式伪造这种行为的中间件。否则 dispatch 调用的结果是 POJO 而不是 Promise。
  • @YuryTarabanko 谢谢你,这是解决方案,我在 lib 的问题中找到了解决方法

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


【解决方案1】:

基于@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]);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-01-26
    • 2017-03-03
    • 1970-01-01
    • 2017-10-14
    • 2017-03-04
    相关资源
    最近更新 更多