React Redux异步操作测试 [英] React Redux async action testing

查看:113
本文介绍了React Redux异步操作测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编写了测试异步操作的测试。我目前收到以下错误 TypeError:无法读取poperty'然后'未定义并且它指向我的代码中的以下行

I have my test written to test async actions. I'm currently getting the following error TypeError: Cannot read poperty 'then' of undefined and it is pointing to the following line in my code

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

这是我的代码:

async actions test:

async actions test :

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

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

This is the first time testing async actions so I'm not sure what's going wrong.

推荐答案

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

Try using redux-mock-store instead of redux createStore(). This is a mock store for testing async action creators and middleware. The Github page also includes some examples how to use it.

编辑:

修改你的内容时会发生什么动作创建者,以便它返回 axios.get(MOVIES_API)的结果?

What happens when you modify your action creator so that it returns the result of axios.get(MOVIES_API)?

这篇关于React Redux异步操作测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆