Testing Thunks - Tuong-Nguyen/JavaScript-Structure GitHub Wiki
Purpose
- Test ajax call
- Assert executed actions
Need
Mock 2 things:
- Store: using
redux-mock-store
- HTTP calls: using
nock
(we add wiki for mock api so there is nonock
)
Steps
Import
thunk
- Redux mock store
import thunk from 'redux-thunk';
import configureMockStore from 'redux-mock-store';
Create mock store with initial state
const store = mockStore({courses:[]});
thunk
middleware
Configure mock store with const middleware = [thunk];
const mockStore = configureMockStore(middleware);
callback
Define the test case with it('should create BEGIN_AJAX_CALL and LOAD_COURSES_SUCCESS when loading courses', (done) => {});
Mock the API to return Promise.
Dispatch the actions and assert the promise callback
store.dispatch(courseActions.loadCourses()).then(()=>{
const actions = store.getActions();
expect(actions[0].type).toEqual(types.BEGIN_AJAX_CALL);
expect(actions[1].type).toEqual(types.LOAD_COURSES_SUCCESS);
});
Tell Mocha the async work is completed
done();