I have an action:
export const GetChatList = userStatus => {
return dispatch => {
dispatch({
type: MessagesActionTypes.GET_MESSAGES_LIST.REQUEST,
payload: {}
});
axios
.get(config.apiUrl + config.methods.getMessagesList, { params: { accountType: userStatus } })
.then(res => {
dispatch({
type: MessagesActionTypes.GET_MESSAGES_LIST.SUCCESS,
payload: res.data
});
})
.catch(err => {
dispatch({
type: MessagesActionTypes.GET_MESSAGES_LIST.ERROR,
payload: 'error text'
});
});
};
};
And I tried to write a test for this action:
const middlewares = [thunk];
const mockStore = configureMockStore(middlewares);
describe('Messages actions', () => {
afterEach(() => {
fetchMock.restore();
});
it('GetChatList', () => {
fetchMock.get(config.apiUrl + config.methods.getMessagesList, { params: { accountType: 1 } });
const expectedActions = [
{ type: MessagesActionTypes.GET_MESSAGES_LIST.REQUEST },
{
type: MessagesActionTypes.GET_MESSAGES_LIST.SUCCESS,
payload: ...somePayload
},
{
type: MessagesActionTypes.GET_MESSAGES_LIST.ERROR,
payload: 'error text'
}
];
const store = mockStore({...initialState});
return store.dispatch(GetChatList(1)).then(() => expect(store.getActions()).toEqual(expectedActions));
});
});
And then I get an error: TypeError: Cannot read property 'then' of undefined Why is this happening and how to properly test this action? What are my mistakes?
fetch-mock
mocks HTTP requests made usingfetch
. But you are usingaxios
.You should return the promise created by
axios.get()
in the thunk. So that you can callstore.dispatch(GetChatList(1)).then()
method.You can use
jest.spyOn(axios, 'get')
to mockaxios.get()
method and its resolved/rejected value.E.g.
thunk.ts
:thunk.test.ts
:Test result: