React Redux异步操作测试

时间:2016-07-13 15:25:22

标签: javascript reactjs redux react-redux

我编写了测试异步操作的测试。我目前收到以下错误TypeError: Cannot read poperty 'then' of undefined并且它指向我的代码中的以下行

return store.dispatch(actions.fetchMovies()).then(() => {

这是我的代码:

异步操作测试:

import { createStore, applyMiddleware } from 'redux';
import initialState from '../reducers/initialState';
import rootReducer from '../reducers/index';
import thunk from 'redux-thunk';
import * as actions from './actions';
import * as ActionTypes from '../constants/constants';
import nock from 'nock';
import { expect } from 'chai';
import API_KEY from '../config/config';

const MOVIES_API = 'https://api.themoviedb.org/3/discover/movie?api_key='+API_KEY;

describe('async actions', () => {
  afterEach(() => {
    nock.cleanAll();
  });

  it('creates FETCH_MOVIES_SUCCESS when fetching movies is complete', () => {
    nock(MOVIES_API)
      .get()
      .reply(200, {data: {results: [{title: 'Batman vs Superman'}]}});

    const expectedActions = [
      { type: ActionTypes.FETCH_MOVIES },
      { type: ActionTypes.FETCH_MOVIES_SUCCESS, data: {results: [{title: 'Batman vs Superman'}]}}
    ];

    const store = createStore(rootReducer, initialState, applyMiddleware(thunk));

    return store.dispatch(actions.fetchMovies()).then(() => {
        expect(store.getActions()).to.deep.equal(expectedActions);
      });
  });
});

行动:

import axios from 'axios';

import * as constants from '../constants/constants';
import API_KEY from '../config/config';


export const fetchMovies = () => {
  const MOVIES_API = 'https://api.themoviedb.org/3/discover/movie?api_key='+ API_KEY;

  return dispatch => {
    dispatch({
      type: constants.FETCH_MOVIES
    });
    axios.get(MOVIES_API).then(function(response) {
      dispatch({
        type: constants.FETCH_MOVIES_SUCCESS,
        data: response.data.results
      });
    })
    .catch(function(res) {
      dispatch({
        type: constants.FETCH_MOVIES_ERROR,
        msg: res.message
      });
    });
  };
};

这是第一次测试异步操作,所以我不确定出了什么问题。

2 个答案:

答案 0 :(得分:2)

这是因为你的行为没有回复承诺 - 改变你的行动以返回可以等待的承诺。这不是必需的,但如果你想知道你的API调用何时完成(即你的单元测试想知道在这种特殊情况下),那么你可以返回一个承诺作为行动的便利副作用: / p>

export const fetchMovies = () => {
  const MOVIES_API = 'https://api.themoviedb.org/3/discover/movie?api_key='+ API_KEY;

  return dispatch => {
    dispatch({
      type: constants.FETCH_MOVIES
    });

    // Return a promise
    return axios.get(MOVIES_API).then(function(response) {
      dispatch({
        type: constants.FETCH_MOVIES_SUCCESS,
        data: response.data.results
      });
    })
    .catch(function(res) {
      dispatch({
        type: constants.FETCH_MOVIES_ERROR,
        msg: res.message
      });
    });
  };
}

答案 1 :(得分:0)

尝试使用redux-mock-store代替redux createStore()。这是一个用于测试异步操作创建器和中间件的模拟存储。 Github页面还包含一些如何使用它的示例。

编辑:

修改动作创建者以使其返回axios.get(MOVIES_API)的结果时会发生什么?