Unit Testing Redux Asynchronous Action Creators - HashedIn Technologies

Unit Testing Redux Asynchronous Action Creators

Technology - 17 Apr 2018
Kousick S

This article is a part of the series on how to unit test a react/redux application and is intended to share some knowledge on how to test redux asynchronous action creators and redux reducers. I would recommend you to read the primary article and Part 1 of the series before you dive into this.

Testing Redux Asynchronous action creators

Assuming that if you are reading this, you should be knowing what action creators are, let me move to asynchronous action creators. Your actions may make asynchronous HTTP requests to get data, and testing them is important. Action creators are responsible for dispatching the right actions to the redux store.

In our ReferralJobs application, we have used axios to make HTTP requests. You may alternatively use any library(ex: fetch) to make your HTTP requests. In order to test this action creator, we will have to mock the HTTP request and the response. Also, we need to mock the redux store to handle the actions.

For this, we have used redux-mock-store to mock the store and axios-mock-adapter to mock our axios HTTP requests.(If you are using anything apart from axios to perform HTTP request, consider using nock).

In our test case, we are simply using the libraries and setting up the mocks and creating a mock store for testing the action creators.

Once our mockStore is ready, in our test case we mock the HTTP request that is expected to be made and also gives it a sample response.

When an action creator is called, it is expected to dispatch actions to the store and this is a known object defined as expectedActions in our test case.

We then dispatch the action creator into our store with empty data, now the action creator is expected to make a HTTP request and dispatch necessary actions into the store.

We are testing this post the timeout as the http request is an asynchronous call(this is a hack for getting it working on axios-mock-adapter, if you are using nock the timeout is not required)

Testing Redux Reducers

Testing reducers are straightforward and are not dependent on any setup. Any reducer, when called with an action type, must modify the state and return the state back. Hence we only have to test a state object.

In our test case , we are passing a payload to the action type and we expect the state to change with the appropriate payload.

Redux handles the state of data flow within a react application, writing Unit Tests for its action creators and reducers would bring in a lot of value to your application’s quality. I hope this article helped you.

If you have not gone through the previous version of this series, I would recommend you to also read both the primary article and the Part 1 of this series.

Free tag for commerce

E-book on Digital Business Transformation