React Redux 异步动作测试

IT技术 javascript reactjs redux react-redux
2021-05-03 05:37:25

我写了我的测试来测试异步操作。我目前收到以下错误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个回答

这是因为您的操作不会返回Promise - 更改您的操作以返回可以等待的Promise。这不是必需的,但是如果您想知道 API 调用何时完成(即在这种特殊情况下您的单元测试想知道),那么您可以返回一个 promise 作为操作的便利副作用:

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

;

尝试使用redux-mock-store而不是reduxcreateStore()。这是一个用于测试异步操作创建者和中间件的模拟商店。Github 页面还包含一些如何使用它的示例。

编辑:

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