I keep getting "localStorage is not defined" in Jest tests which makes sense but what are my options? Hitting brick walls.
相关问题
- “No reducer provided for key X” console.error in r
- Nest JS - Issue writing Jest Test Case for a funct
- MongoError: pool is draining, new operations prohi
- jest test fails with refs and Form
- Jest and SCSS variables
相关文章
- React testing library: Test attribute / prop
- React/JestJS/Enzyme: How to test for ref function?
- enzyme simulate submit form, Cannot read property
- How to simulate mouse over event on a div using en
- React Native + Jest EMFILE: too many open files er
- How to set a test for multiple fetches with Promis
- How to spy on window.scrollTo in Jest?
- How does module resolution in TypeScript work for
Riffed off some other answers here to solve it for a project with Typescript. I created a LocalStorageMock like this:
Then I created a LocalStorageWrapper class that I use for all access to local storage in the app instead of directly accessing the global local storage variable. Made it easy to set the mock in the wrapper for tests.
As @ck4 suggested documentation has clear explanation for using
localStorage
in jest. However the mock functions were failing to execute any of thelocalStorage
methods.Below is the detailed example of my react component which make uses of abstract methods for writing and reading data,
Error:
Fix:
Add below mock function for jest (path:
.jest/mocks/setUpStore.js
)Snippet is referenced from here