Mocking local storage with Jest

Marek Rozmus
2 min readOct 15, 2022

--

Photo by Lia Trevarthen on Unsplash

How should we test the component that is using local storage?

Here is a simple component that is using local storage.

To test such component we should mock the local storage methods that we are using. There is no point in testing the local storage functionality itself (unless we are writing unit tests for local storage functionality).

We don’t need to test if local storage actually wrote some data, we want to test if our component called the locale storage’s method and that it called it with expected parameters.

We can mock it as any other property of window object. I wrote about mocking window object here: Mocking window object with Jest.

And the tests:

spyOn usage to mock local storage

We can also achieve same setup but with spyOn method.

In this case the original implementation of local storage method will be executed. But we can easily fix it with mocking the implementation:

Simpler and cleaner approach than the first one with mocking.

The code

All the code can be find in this article’s repository:
https://github.com/marekrozmus/blog-mocking-local-storage-with-jest

--

--

Marek Rozmus
Marek Rozmus

Written by Marek Rozmus

Senior Frontend Engineer at GoStudent

Responses (1)