Jest "SecurityError: localStorage is not available"
jsdom refuses localStorage/sessionStorage access when the document origin is "opaque" - the default about:blank. The spec forbids storage on opaque origins, so jsdom throws a SecurityError.
What this error means
Any code touching localStorage under jsdom throws SecurityError: localStorage is not available for opaque origins. It is deterministic and tied to the jsdom URL, not to the test logic.
SecurityError: localStorage is not available for opaque origins
at Window.get localStorage (node_modules/jsdom/lib/jsdom/browser/Window.js)Common causes
Default opaque jsdom origin
With no configured URL, jsdom runs at about:blank, an opaque origin. Per the HTML storage spec, localStorage on an opaque origin must throw.
No storage mock provided
If you do not give jsdom a real http(s) origin, you must instead stub localStorage yourself; otherwise every access errors.
How to fix it
Give jsdom a concrete origin
Set a real URL so the origin is no longer opaque and storage works.
// jest.config.js
module.exports = {
testEnvironment: 'jsdom',
testEnvironmentOptions: { url: 'http://localhost/' },
};Mock storage in setup
// jest.setup.js
const store = {};
global.localStorage = {
getItem: (k) => store[k] ?? null,
setItem: (k, v) => { store[k] = String(v); },
removeItem: (k) => { delete store[k]; },
clear: () => { for (const k in store) delete store[k]; },
};How to prevent it
- Set a non-opaque
urlintestEnvironmentOptions. - Centralize a storage mock in a shared setup file.
- Reset storage between tests to avoid cross-test leakage.