【问题标题】:Error Promise is not defined when I start my unit test on async action Redux当我开始对异步操作 Redux 进行单元测试时,未定义错误承诺
【发布时间】:2016-08-01 08:52:01
【问题描述】:

我正在用 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));
    });
  }
}

我希望你能帮助我 谢谢

【问题讨论】:

    标签: javascript unit-testing reactjs redux


    【解决方案1】:

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

    Axios upgrade guide 中所述,使用 polyfill 应该可以工作。

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

    【讨论】:

      【解决方案2】:

      如果你像我一样使用babel,你可以使用babel-polyfill

      $ npm install --save babel-polyfill

      import "babel-polyfill";

      我也先尝试过es6-promise,不幸的是没有运气。

      但我发现这个简短、清晰、完整且正确的主题答案:axios IE promise doesn't work

      【讨论】:

        猜你喜欢
        • 2018-05-25
        • 2017-10-14
        • 1970-01-01
        • 1970-01-01
        • 2019-04-18
        • 1970-01-01
        • 1970-01-01
        • 2018-01-30
        相关资源
        最近更新 更多