Test case using jest: Redux Reducer

We are going to write test case for reducer which is quite simple compare to action and component test case.From reducer test case file we will pass the dummy data and will test that the initial state object is updating based on data we are passing from test case or not.

Gorakh Nath
2 min readApr 10, 2019

First add the dummyReducer.js file and add the code for reducer, i am sharing dummy code structure of reducer below:-

import * as Actiontypes from ‘./ActionTypes’;

const initialState ={recordsByName : null,recordsByID:null,recordsByState:null};

export const dummyReducer = (state=initialState,action) =>{

switch(action.type)

{

case Actiontypes.SEARCH_BY_NAME :

return {…state,…action.data};

case Actiontypes.SEARCH_BY_ID:

return {…state,…action.data};

case Actiontypes.SEARCH_BY_STATE :

return {…state,…action.data};

default :

return state;

}

}

Now add file dummyReducer.test.js and add the following code:-

import React from “react”;

import { dummyReducer } from “./dummyReducer”;

import * as Actiontypes from “./ActionTypes”;

const initialState = {

recordsByName: null,

recordsById: null,

recordsByState: null

};

describe(“Checking the dummy reducer”, () => {

test(“check reducer data flow for name search”, () => {

expect(

dummyReducer(initialState, {

type: Actiontypes.SEARCH_BY_NAME,

data: { recordsByName: “Gorakh” }

})

).toEqual({

recordsByName: “Gorakh”,

recordsById: null,

recordsByState: null

});

});

test(“check reducer data flow for id search”, () => {

let payload = {

recordsById: “Gorakh”

};

expect(

dummyReducer(initialState, {

type: Actiontypes.SEARCH_BY_ID,

data: payload

})

).toEqual({

recordsByName: null,

recordsById: “Gorakh”,

recordsByState: null

});

});

test(“check reducer for state search”, () => {

let payload = {

recordsByState: “Gorakh”

};

expect(

dummyReducer(initialState, {

type: Actiontypes.SEARCH_BY_STATE,

data: payload

})

).toEqual({

recordsByName: null,

recordsById: null,

recordsByState: “Gorakh”

});

});

});

Explanation

In the test case mentioned the same action type that is use in the reducer to test that.From test case just pass the dummy data and check whether it is updating in the reducer or not.One by one we are passing the data and testing in above code.

Wrap up

Now you can run the command npm test dummyReducer.test and check the output:-

Test case reducer

--

--