Setup and Integration
Learn how to set up and integrate tests we have created.
We'll cover the following
Introduction
The role of the integration tests is to verify that all the parts of the application work correctly together. A comprehensive unit test suite will ensure all the reducers, action creators, middleware, and libraries are correct. We will try to run integration tests together in a single test to check system-wide behavior.
As an example of an integration test, we will verify that when the fetchRecipes()
action creator is dispatched, data is correctly fetched from the server, and the state is updated. In this flow, we will check whether the API middleware is set up correctly, all the required action creators are correct, and the recipes reducer updates the state as needed.
Basic setup
Since the integration tests will be using the real store, we can simply require and initialize it as in our regular application:
import store from 'store';
describe('integration', () => {
it('should fetch recipes from server', () => {
// TODO
});
});
Basic integration test
Our test will include four steps:
- Verify the initial state.
- Mock the data returned from the server.
- Dispatch the action created by
fetchRecipes()
. - Verify that our state’s
recipes
key holds the data returned from the server.
The full test looks like this:
// Full integration test
import store from 'store';
import { fetchRecipes } from 'actions/recipes';
import { mockRequest } from 'axios';
describe('integration', () => {
it('should fetch recipes from server', () => {
const data = [{ title: 'test' }];
expect(store.getState().recipes).toEqual([]);
mockRequest('recipes.json', 200, JSON.stringify(data));
return store.dispatch(fetchRecipes())
.then(() => expect(store.getState().recipes).toEqual(data));
});
});
To ensure our reducer updates the state, we first verify that our initial recipes
list is empty and check that it was changed to contain the server-returned data after the fetchRecipes()
action was completed.
As can be seen from this simple test, doing integration tests in Redux is usually fairly straightforward. Because actions drive everything, in most cases, our integration tests will follow the four steps outlined previously: we verify the initial state of the system, mock any external dependencies, dispatch an action, and verify that the state has changed and any external APIs were called as expected.
Get hands-on with 1400+ tech skills courses.