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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With