Hey there ! I'm trying to test Redux actions with Jest, using Promises.
My action function is the following :
export function exportCurrentConfig() {
return function(dispatch, getState) {
const result = postJSON( some_url_im_requesting, {})
.then(data => {
return (dispatch) => {
dispatch({
type: 'GET_EXPORT_ID',
payload: data
})
}
})
return result
}
}
This postJSON
function is mocked :
// __mocks__/fetch.js
export function postJSON (url, data) {
return new Promise((resolve, reject) => {
process.nextTick(
() => {}
)
})
}
and then, in my specs i'm trying to check the final result when all the promises are resolved :
// __tests__/components/exports-actions-test.js
jest.unmock('../')
jest.unmock('../actions')
jest.unmock('redux-mock-store')
jest.unmock('redux-thunk')
import * as actions from '../actions'
import configureMockStore from 'redux-mock-store'
import thunk from 'redux-thunk'
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
describe('Dataset actions', () => {
it('exportCurrentConfig - default parameters', () => {
const expectedActions = [{
type: actions.GET_EXPORT_ID
}]
const store = mockStore({})
return store
.dispatch(actions.exportCurrentConfig({}))
.then(() => {
expect(store.getActions()).toEqual(expectedActions)
})
})
})
The mock function is called and returning the promise, the action is returning something, but i'm getting this error on the specs :
Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
(using babel-jest 14.1.0 and jest-cli 12.0.2)
EDIT: Also tried to redefine the global definition of Promise, and it's also breaking the specs..
Thanks for your help !
Got the problem, I need to resolve the promise in the mock function :
// __mocks__/fetch.js
export function postJSON (url, data) {
return new Promise((resolve, reject) => {
process.nextTick(
() => resolve({})
)
})
}
Adding this comment here describing the reason for this error message for people that may find this page in future.
That happens because you have a dispatch function nested inside your promise.
dispatch({
type: 'GET_EXPORT_ID',
payload: data
})
Remember that dispatch() is async and needs to be resolved. That's why you were getting the error msg.
I'm just here to chime in that I solved this error with utilizing the done()
call.
I was testing a redux action, and from the console.log
s I was using, all the outputs were expected, the resolve()
and dispatch()
were assumedly being called within the success callback for a PUT
via axios
.
Most helpful comment
Adding this comment here describing the reason for this error message for people that may find this page in future.
That happens because you have a dispatch function nested inside your promise.
Remember that dispatch() is async and needs to be resolved. That's why you were getting the error msg.