Test Case using jest : Redux Action

We can setup react application using command npm create-react-app

Gorakh Nath
2 min readApr 7, 2019

Add the following dependencies in package.json file and run npm install

add the redux dependencies in package.json
add fetch mock and test dependency in package.json

Add js file named as dummyAction:-

require(“es6-promise”).polyfill();

require(“isomorphic-fetch”);

const myHeaders = new Headers({

“Content-Type”: “application/json”,

Accept: “application/json”

});

export const displayName = name => {

return { type: “Display_Name”, data: name};

};

export const getName = (empId) => {

return dispatch => {

return fetch(`https://dev.example.com:60101/GetName/ + ${empId}`, {

headers: myHeaders

}).then(response => {

if (response.status === 200) {

return response.json();

}

}).then(name => {

if (name !== undefined && isEmpty(name) === false) {

dispatch(displayName(name));

}

})

.catch(ex =>console.log(ex));

};

};

Now add a file dummyAction.test and write test case:-

import * as actions from “./dummyAction”;

import thunk from “redux-thunk”;

import fetchMock from “fetch-mock”;

import configureMockStore from “redux-mock-store”;

const middlewares = [thunk];

const mockStore = configureMockStore(middlewares);

describe(“Test Action- dummyAction”, () => {

afterEach(() => {

fetchMock.reset();

});

it(“Test displayName method with valid input”, async () => {

// Create a store with the provided object as the initial state

const store = mockStore({});

//create the header that should match with the action header

const myHeaders = new Headers({

“content-type”: “application/json”,

Accept: “application/json”

});

// create the dummy response that should return after fetch call

let response = {

status: 200,

body: {

name: “gorakh”

}

};

//create the expected action that should dispatch

const expectedActions = [

{

type: “Display_Name”,

data: { name: “gorakh” }

}

];

//mock the fetch call

let empId = “000000”; //mock empId

let url = `https://dev.example.com:60101/GetName/ + ${empId}`; //construct url

fetchMock.mock(url, response); //call mock fetch

//call the action that need to test

await store.dispatch(actions.getName(empId));

//call the test condition

expect(store.getActions()).toMatchObject(expectedActions);

});

});

Wrap up:-

Now run the command:

npm test dummyAction.test

The test should pass and it should shows the following output.

--

--