I'm learning to write tests for action creators with Jest and Enzyme. This is an action creator that I am using with React Native.
Please consider the code below:
import {
FETCH_FAIL
} from './types';
export const fetchFail = (dispatch) => {
dispatch({
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
});
};
I wrote the following test for this action creator:
import configureStore from 'redux-mock-store';
import thunk from 'redux-thunk';
const middlewares = [thunk];
const mockStore = configureStore(middlewares);
test('should fail fetch', async () => {
const payload = {
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
}
const store = mockStore({ data:[], isConnected: false });
expect(store.dispatch(actions.fetchFail())).toEqual(payload);
})
My test fails with the following result:
TypeError: dispatch is not a function
What am I doing wrong?
First you will need to return the dispatched action from your thunk
export const fetchFail = (dispatch) => {
return dispatch({
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
});
};
And then don't call the thunk but pass the reference(remove the parentheses) because the thunk middleware is calling your action passing dispatch as the first argument when the action is a function
test('should fail fetch', async () => {
const payload = {
type: FETCH_FAIL,
payload: "An error occurred. Try again later."
}
const store = mockStore({ data:[], isConnected: false });
// removed the parentheses around fetchFail()
expect(store.dispatch(actions.fetchFail)).toEqual(payload);
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With