Jest Environment

Lets start with the problem we face while running unit tests using Jest. In the snap below, you can see Local Storage is not defined., which shocks most frontend developers, on how could that local storage be not available.

Problem

This got me thinking.. what all are there in the environment to begin with!! I switched to debug mode, and tried inspecting the unit tests in the browser devtools. You can do this by using below command.

node --inspect-brk node_modules/.bin/jest --runInBand <testfile>

So here is how the test file would show up in debugging mode, in the browser devtools. We can type in, into the devtools console and see what is the value of any object. So, I typed in “window”. To my surprise, it’s undefined. So basically what we have is a javascript runtime shell which doesn’t have much. Check the snaps below.

Window undefined

So, we see there are some functions that are made available for the test environment runtime.

Other functions

As expected, there is no local storage in the environment. All we have to do is create a mock, with the expected signature, and attach into the test environment.

Creating Local Storage mock

In my test case, I am expecting getItem method call on the local storage. I am creating a jest mock function with a default return value of null.

let localStorageSpy = jest.fn().mockReturnValue(null);

beforeEach(() => {
  global.localStorage = {
    getItem: localStorageSpy,
  };
});

Where needed, I would update the jest spy to return appropriate value in the unit test as below. As local storage getItem would return a string, I am returning a string in the snippet.

localStorageSpy.mockReturnValue('{"age":10}');

The moment of truth, on the assertions part - you can either assert if the function got called or called with a value.

Assertions

expect(localStorageSpy).toHaveBeenCalled();

expect(localStorageSpy).toHaveBeenCalledWith("XYZ");

Reset!

Finally once you are done, reset the environment.

global.localStorage = undefined;

Hope this clarified on unit testing local storage related features. Follow for more!