I have following function.
const loadUsers= () => { return async (dispatch) => { dispatch(userRequest()); let response= null try { response= await UserService.getUser(); dispatch(userLoading()); } catch (error) { dispatch(userError(error)); } finally { dispatch(userSuccess(response)); } }; };
With the following unit test I was abale to hit the “dispatch(userRequest());”
describe('user thunk', () => { it('dispatches a userRequest', async () => { const dispatch = jest.fn(); await loadUsers()(dispatch); expect(dispatch).toHaveBeenCalledWith(userRequest()); }); });
However I couldn’t figure out how to test lines and below response= await UserService.getUser();
. Even though the function is not complex and I won’t have much value for writing complex test, I need it for my pipeline to build.
Any help will be appreciated.
Thanks in advance.
UPDATE-> User Service
import axios from 'axios'; const USERS_ENDPOINT = '/user'; export const getUser= async () => { const response = await axios.get(PRODUCTS_ENDPOINT, {}); return response.data; }; export default getUser;
Advertisement
Answer
After days of research, I ended up testing the logic the following way.
JavaScript
x
45
45
1
import thunk from 'redux-thunk';
2
import configureStore from 'redux-mock-store';
3
import * as reactRedux from 'react-redux';
4
5
import axios from 'axios';
6
const middlewares = [thunk];
7
const mockStore = configureStore(middlewares);
8
9
describe('load user thunk', () => {
10
it('dispatches load user and error on call when API is not mocked', async () => {
11
const store = mockStore({});
12
const requestDispatch= userRequest();
13
const errorDispatch= userError("Mock Message");
14
15
await store.dispatch(await loadUsers());
16
const actionsResulted = store.getActions();
17
const expectedActions = [
18
requestDispatch,
19
errorDispatch,
20
];
21
expect(actionsResulted.length).toEqual(expectedActions.length);
22
expect(actionsResulted[0].type).toEqual(expectedActions[0].type);
23
expect(actionsResulted[1].type).toEqual(expectedActions[1].type);
24
});
25
26
it('dispatches load user and success on call when API is mocked', async () => {
27
const store = mockStore({});
28
const requestDispatch= userRequest();
29
const successDispatch= userSuccess("Mock Data");
30
jest
31
.spyOn(axios, 'get')
32
.mockResolvedValue({ status: 200, data: "Mock Data"});
33
34
await store.dispatch(await loadUsers());
35
const actionsResulted = store.getActions();
36
const expectedActions = [
37
requestDispatch,
38
successDispatch,
39
];
40
expect(actionsResulted.length).toEqual(expectedActions.length);
41
expect(actionsResulted[0].type).toEqual(expectedActions[0].type);
42
expect(actionsResulted[1].type).toEqual(expectedActions[1].type);
43
44
});
45