Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: sessionStorage is not defined in jest unit test case

Tags:

reactjs

jestjs

I want to write jest unit test case for one action in ReactJS which is using session storage but I am getting error that sessionStorage is not defined.

any solution how to deal with that?

like image 923
vinod Avatar asked Dec 21 '17 14:12

vinod


1 Answers

To solve this problem you need to mock the session storage.

One simple solution is to use a plugin, like the mock-local-storage package (inspired by StackOverflow answers). It mocks the localStorage (and sessionStorage) for headless unit tests. Simply install it:

npm install mock-local-storage --save-dev

and then in you, package.json under the "jest" configuration add:

...
"jest": {
  ...
  "setupTestFrameworkScriptFile": "mock-local-storage"
}
...

This will add mocked localStorage and sessionStorage for all test cases, you do not need changes in every file.

Instead of using npm package, you can also put your code in a file and specify file-location here under setupTestFrameworkScriptFile. Your code should be similar to this one.

Here's a related thread. Credits for the solution.

like image 116
Kaloyan Kosev Avatar answered Sep 25 '22 02:09

Kaloyan Kosev