我编写了测试异步操作的测试。我目前收到以下错误 TypeError: Cannot read poperty 'then' of undefined
并且它指向我代码中的以下行
return store.dispatch(actions.fetchMovies()).then(() => {
这是我的代码:
异步 Action 测试:
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);
});
});
});
Action :
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
});
});
};
};
这是第一次测试异步操作,所以我不确定出了什么问题。
最佳答案
这是因为您的操作没有返回 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
});
});
};
}
;
关于javascript - React Redux 异步 Action 测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38355847/