javascript - 开玩笑 - 测试给出错误 TypeError: Cannot read property 'then' of undefined
问题描述
当我运行测试时,它给了我一个错误 TypeError: Cannot read property 'then' of undefined,我试图在 Docs 上寻找一些修复,但我没有找到解决这个问题的方法,任何想法解决这个问题将不胜感激谢谢。
联系actions.js
export function getContacts() {
return function(dispatch) {
dispatch({type: 'GET_CONTACTS_PENDING'})
axios.get('http://127.0.0.1:8000/api/contacts', {
})
.then((response) => {
dispatch({type: 'GET_CONTACTS', payload: response.data})
dispatch(hideLoading())
})
.catch((error) => {
dispatch({type: 'CONTACT_ERROR', payload: error})
})
}
}
app.spec.js
import React from 'react';
import { shallow, mount } from 'enzyme';
import renderer from 'react-test-renderer';
import MockAdapter from 'axios-mock-adapter';
import configureMockStore from 'redux-mock-store';
import nock from 'nock';
import axios from 'axios';
import moxios from 'moxios';
import expect from 'expect';
import thunk from 'redux-thunk';
import { Provider } from 'react-redux';
import * as actions from '../src/actions/contact-actions';
import * as types from '../src/constants/action-types';
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('async actions', () => {
afterEach(() => {
nock.cleanAll();
});
it('creates GET_CONTACTS when fetching contacts has been done', () => {
const store = mockStore({});
const contacts = {};
nock('http://127.0.0.1:8000')
.get('/api/contacts')
.reply(200, { body: { contacts: [{ first_name: 'shadow', last_name: 'madow', phone: 5566, email: 'shadow@yahoo.com' }] } });
const expectedActions = [
{ type: types.GET_CONTACTS, body: { contacts: [{ first_name: 'shadow', last_name: 'madow', phone: 5566, email: 'shadow@yahoo.com' }] }}
];
return store.dispatch(actions.getContacts()).then(() => {
// return of async actions
expect(store.getActions()).toEqual(expectedActions);
});
});
});
解决方案
请务必从 getContacts() 中的匿名函数返回承诺:
export function getContacts() {
return function(dispatch) {
dispatch({type: 'GET_CONTACTS_PENDING'})
axios.get('http://127.0.0.1:8000/api/contacts', { // THIS LINE
})
...
改变这个:
axios.get('http://127.0.0.1:8000/api/contacts', {
对此:
return axios.get('http://127.0.0.1:8000/api/contacts', {
现在它缺少一个 return 语句,所以返回undefined
。
推荐阅读
- r - 如何从 R 中长度不同的两个数据框中找到元素?
- typescript - 我可以有一个 Typescript 函数,它返回一个标量或数组值,而调用者不需要转换输出
- sql - 1 记录为多条记录
- python - 用通过迭代计算的函数填充 numpy 矩阵
- java - Java 2d:减慢旋转速度(就像命运之轮)
- php - 如何上传图片随机名称?
- javascript - 强制 selectize.js 仅显示以 Shiny 中的用户输入开头的选项
- python - tensorflow-gpu 从 systemd 服务初始化失败
- c# - 无法删除对象,因为在删除项目时ObjectStateManager错误中找不到
- asp.net - 将 ZK 考勤设备的数据与 Web 应用程序集成和同步