gpt4 book ai didi

javascript - 当我开始对异步操作 Redux 进行单元测试时,未定义错误 promise

转载 作者:行者123 更新时间:2023-11-27 23:06:27 25 4
gpt4 key购买 nike

我正在使用 JavaScript 中的 REACT + REDUX 开发一个 Web 应用程序,一切正常 ^^

但我正在尝试使用 mocha 对异步操作进行单元测试,但遇到了错误

 1) async actions creates login async action:
ReferenceError: Promise is not defined
at Axios.request (node_modules/axios/lib/axios.js:62:17)
at Axios.(anonymous function) [as post] (node_modules/axios/lib/axios.js:113:17)
at Function.wrap (node_modules/axios/lib/helpers/bind.js:9:15)
at index.js:27:11
at Object.dispatch (node_modules/redux-thunk/lib/index.js:12:16)
at Context.<anonymous> (test.js:28:11)

这是我的 test.js

import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import * as actions from '../../src/actions/index';
import * as types from '../../src/constants/constants_session';
import nock from 'nock';
import ReduxPromise from 'redux-promise';
import axios from 'axios';
import expect from 'expect'; // You can use any testing library

const middlewares = [ thunk, ReduxPromise ]
const mockStore = configureMockStore(middlewares)

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

it('creates login async action', (done) => {
nock('http://127.0.0.1:5000')
.get('/auth')
.reply(200)

const expectedActions = [
{ type: types.LOGGED_SUCCESSFULLY }
]
const store = mockStore()

store.dispatch(actions.login())
.then(() => { // return of async actions
expect(store.getActions()).toEqual(expectedActions)
})
.then(done) // test passed
.catch(done) // test failed
})
})

这是我的action.js

export function login(accountDetails) {
const url = `${ROOT_URL}/auth/`;
return function(dispatch) {
axios.post(url, accountDetails)
.then(function(response) {
if (response.status >= 200 && response.status < 300) {
dispatch(loginSuccess(response.data.response.data.user));
browserHistory.push("/admin");
}
else
dispatch(loginError(response.data.response.message));
})
.catch(function(response) {
dispatch(loginError(response.data.response.message));
});
}
}

希望你能帮助我谢谢

最佳答案

您的测试环境中似乎缺少 Promise,Axios 正在使用该环境,它是 ES6 的一部分。

使用 polyfill 应该可以,如 Axios upgrade guide 中所述。 .

require('es6-promise').polyfill();
var axios = require('axios');

关于javascript - 当我开始对异步操作 Redux 进行单元测试时,未定义错误 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36544532/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com