Luckystrike561 Luckystrike561 - 1 month ago 37
React JSX Question

Error Promise is not defined when I start my unit test on async action Redux

I'am developping a web app with REACT + REDUX in javascript everything is working ^^

but I'am trying to make unit test on async action with mocha and I'am stuck with an error

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)


this is my 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
})
})


and this is my 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));
});
}
}


I hope you can help me
thanks

Answer

You seem to be missing Promise in your test environment, which Axios is using and which is part of ES6.

Using a polyfill should work, as described in Axios upgrade guide.

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