Introduction to Testing your Redux Code

Fatimat Gbajabiamila
Junior Dev Diaries
Published in
3 min readAug 16, 2018

If you are wondering how to test your redux code, read on!

Prerequisites for better understanding of post

  • Basic understanding of redux
  • Basic understanding of Test Driven Development
  • Using Jest for testing

What you’ll learn

  • How to test an action creator
  • How to test test a reducer
  • Useful modules you can use when testing

Dismantling redux and its jargons

Redux is a state(i.e data) management tool for web applications and can be used with many libraries and frameworks.

All state in redux are stored and managed via redux store and is created using the createStore() method. The create store method takes a **reducer** as its argument.

To update your state in redux you have to dispatch(i.e send) an action using an action creator. An action is an object containing type and often payload. Type describes the action, it is a string and you can name it whatever you want. Payload is the data you want to add to your redux store. Data can be of any data type and you can choose to call it something other than payload but payload is commonly used. Actions are used to pass data to your store.
Action creators are functions that return an action object.

The reducer previously mentioned is a function that communicates with the store. It is a pure function, that is, it takes in the previous state and an action as its arguments and always returns a new state.

Setting up for testing

I will be demonstrating by testing a action creator that logs a user out of your web application.

To get started I will create a test support file. I usually call my file test-support.js.

Testing action creator

Now that the set up is out of the way, I can move on to testing our action creator.

I will first define the action type in a variable

const LOGOUT_USER = “LOGOUT_USER”;

The code below is an action creator that logs out a user from a web app. The action creator makes a call to an api route.

const logout = () => {
return dispatch => {
return axios.get("/api/logout").then(() => {
dispatch({
type: LOGOUT_USER,
payload: false
});
});
};
};

In the code below, I am testing that the logout function defined above is returning the right action for logging out a user. I am going to assume you are familiar with the syntax for testing using jest and not go into much details about that.

Testing reducer

As we know already, a reducer is the function that returns an action and is responsible for updating your state in the store.

Below I am declaring an alert reducer which I will be testing.

const alertReducer = (state = {}, action) => {
switch (action.type) {
case ADD_ERROR:
return { state, ...action.payload };
default:
return state;
}
};

I will write a test to check my state is been updated when an error is dispatched, that is, it does not equal the initial state.

That’s it! I hope you’ve learnt a thing or two.

--

--