Hey guys I am trying to test my async actions creators with Typescript but I am getting a type error that I cannot manage to solve.
This is my actions:
export const loadCurrentUserRequest = () => ({
type: LOAD_CURRENT_USER_REQUEST
})
export const loadCurrentUserSuccess = (payload: any) => ({
type: LOAD_CURRENT_USER_SUCCESS,
payload
})
export const loadCurrentUserFailure = (payload: any) => ({
type: LOAD_CURRENT_USER_FAILURE,
payload
})
And this is my async action creator:
export const loadCurrentUser = () => {
return async (dispatch: Dispatch<any>) => {
dispatch(loadCurrentUserRequest())
try {
const response = await get(`api/currentuser`)
if (!response.ok) {
dispatch(loadCurrentUserFailure({ type: null, message: 'error' }))
} else {
const json = await response.json()
dispatch(loadCurrentUserSuccess(json))
}
return response
} catch (err) {
dispatch(loadCurrentUserFailure({ type: err.name, message: err.message }))
logError(err.name, err.message)
return err
}
}
}
The 'get' function is a middleware I've created to handle 'fetch' GET call (it adds some stuff into the header etc).
This is my test:
it('create an action to load the current user', () => {
const middlewares = [thunk]
const mockStore = configureMockStore(middlewares)
const store = mockStore()
const expectActions = [{ type: LOAD_CURRENT_USER_REQUEST }]
store.dispatch(actions.loadCurrentUser())
expect(store.getActions()).toEqual(expectActions)
})
I am getting this error in my console:
Argument of type '(dispatch: Dispatch<any>) => Promise<any>' is not assignable to parameter of type 'AnyAction'.
Property 'type' is missing in type '(dispatch: Dispatch<any>) => Promise<any>' but required in type 'AnyAction'.
I am not sure what I have done wrong here, I looked at the redux example way to test async action creators and this is similar. I can't figure where my issue is coming from.
I do know that I will have to mock my fetch
API calls and update my expectActions
variable but the code isn't compiling because of that..
Here is the solution:
index.ts
:Unit test:
Unit test result with 100% coverage:
Here is the completed demo: https://github.com/mrdulin/jest-codelab/tree/master/src/stackoverflow/54693637