使用Jest,redux-mock-store和Moxios测试异步调用

时间:2017-08-17 17:00:23

标签: reactjs redux jestjs

我创建了一个简单的案例来测试我的操作,但我的store.dispatch没有返回一个promise。有人能告诉我出了什么问题吗?

Action.js代码:

export const handleSubmit = inputData =>
(dispatch) => {
axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });

};

我的测试:

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import moxios from 'moxios';
import * as actions from './../../../../src/modules/inputData/action';
import { API_URL } from './../../../../src/constants';

const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);

describe('InputData actions', () => {
 test('Test input value update', () => {
 moxios.install();
 moxios.stubRequest(`${API_URL}/process-input/`, { status: 200, response: 'A nice test result' });
 const store = mockStore();

 return store.dispatch(actions.handleSubmit('anyData'))
  .then(() => {
    expect(store.getActions()).toEqual([
      { type: 'UPDATE_OUTPUTT', payload: 'A nice test result' },
    ]);
  });

}); });

返回的错误是:无法读取属性'然后'未定义的

1 个答案:

答案 0 :(得分:2)

您的redux行动不会返回承诺。你应该返回axios.post函数。

export const handleSubmit = inputData =>
(dispatch) => {
return axios.post(`${API_URL}/process-input/`, { input: inputData })
  .then((resp) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: resp.data,
    });
  })
  .catch((e) => {
    dispatch({
      type: 'UPDATE_OUTPUT',
      payload: e.message,
    });
  });
};