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
Great solution from @chiedo
However, we use ES2015 syntax and I felt it was a little cleaner to write it this way.
Currently (Jan '19) localStorage can not be mocked or spied on by jest as you usually would, and as outlined in the create-react-app docs. This is due to changes made in jsdom. You can read about it here https://github.com/facebook/jest/issues/6798 and here https://github.com/jsdom/jsdom/issues/2318.
As a workaround, you can spy on the prototype instead:
Figured it out with help from this: https://groups.google.com/forum/#!topic/jestjs/9EPhuNWVYTg
Setup a file with the following contents:
Then you add the following line to your package.json under your Jest configs
"setupTestFrameworkScriptFile":"PATH_TO_YOUR_FILE",
A better alternative which handles
undefined
values (it doesn't havetoString()
) and returnsnull
if value doesn't exist. Tested this withreact
v15,redux
andredux-auth-wrapper
If using create-react-app, there is a simpler and straightforward solution explained in the documentation.
Create
src/setupTests.js
and put this in it :Tom Mertz contribution in a comment below :
You can then test that your localStorageMock's functions are used by doing something like
inside of your tests if you wanted to make sure it was called. Check out https://facebook.github.io/jest/docs/en/mock-functions.html
or you just take a mock package like this:
https://www.npmjs.com/package/jest-localstorage-mock
it handles not only the storage functionality but also allows you test if the store was actually called.