You don’t need to mock localStorage
with latest jsdom
Suppose you have a localStorage
utility function like this:
1 | // storage-utils.ts |
To test above code, you have the following test file:
1 | // storage-utils.spec.ts |
When you run this test with Jest
1 | # first, navigate to the directory where the test file is located. |
Everything works fine, but localStorage
is only available in browser environment
, and you didn’t mock it, why?
This is because Jest
now use jsdom
as the default environment, and jsdom
has implemented localStorage
and sessionStorage
APIs, so you don’t need to mock them anymore.
To test this, you can find the jest.config.js
file in the root directory of your project, and add the following line to the testEnvironment
property:
1 | module.exports = { |
Then run the test again, you will see the test failed because localStorage
is not available in the node
environment, and you will get the following error:
1 | localStorage is not defined |
Use jsdom
by in test file
Suppose you global jest config is node
(in file jest.config.js
under project root), but you want to use jsdom
in some test cases, you can use the following code in the test file, add @jest-environment jsdom at the top of the file.(Don’t use //
comment, it will not work)
1 | /** |
Mock localStorage
1 | // mockLocalStorage.ts |
Test file, note that we use globalThis
here, it’s environment independently, and works both in node
and browser
environment.
1 | // storage-utils.spec.ts |
References:
- https://jestjs.io/docs/configuration#testenvironment-string - the official document still said that
node
is the default environment, but in my case, it’sjsdom
, not sure why. - https://github.com/jsdom/jsdom/blob/main/Changelog.md#11120