This guide is for a TypeScript setup. If you're using plain JavaScript, you'll still find it helpful, just tweak the type-y bits!
⚡ TL;DR (Copy-Paste Ready)
-
Install dev deps
npm install --save-dev jest ts-jest @types/jest jest-localstorage-mock
-
Update
jest.config.js
// jest.config.js module.exports = { preset: "ts-jest", testEnvironment: "jsdom", setupFilesAfterEnv: ["jest-localstorage-mock"], // …other config… };
-
Write tests
describe("localStorage mock", () => { beforeEach(() => localStorage.clear()); it("stores and retrieves a value", () => { localStorage.setItem("key", "value"); expect(localStorage.getItem("key")).toBe("value"); }); // …more tests… });
Ever had a test accidentally wipe out your real browser data? Or tests fail intermittently because of leftover localStorage? I have, and all I can say is:
"No, thank you." - Me
But fear not! Mocking localStorage
in Jest is the solution. It keeps your tests clean, safe, and gloriously isolated.
🎯 Why Bother Mocking?
Mocking localStorage
with jest-localstorage-mock
gives you:
- 🔁 A fresh, clean slate for every test.
- 🧼 Zero pollution across test cases.
- 🧪 Predictable behavior, no sneaky real browser interactions.
- ⚡ Faster, more reliable test runs.
🧰 What You’ll Need
Assuming you're working in a TypeScript project, install these dev dependencies to get started:
npm install --save-dev jest ts-jest @types/jest jest-localstorage-mock
This will install:
-
jest
: The testing engine. -
ts-jest
: So Jest can understand TypeScript. -
@types/jest
: For autocomplete and type checking. -
jest-localstorage-mock
: ThelocalStorage
mock you didn’t know you needed.
🛠️ Setting Up Jest for localStorage Mocking
Create or update your jest.config.js
at the root of your project:
// jest.config.js
/** @type {import('ts-jest').JestConfigWithTsJest} */
module.exports = {
preset: "ts-jest",
testEnvironment: "jsdom",
transform: {
"^.+\\.tsx?$": "ts-jest",
},
testMatch: ["**/?(*.)+(spec|test).[jt]s?(x)"],
setupFilesAfterEnv: ["jest-localstorage-mock"], // Mocks localStorage before each test
};
With this setup, Jest will:
- Run TypeScript using
ts-jest
, - Mock
localStorage
usingjest-localstorage-mock
, - Fake a browser with
jsdom
becauselocalStorage
is a browser API so we need a pretend browser to make it work.
🧪 Example Tests Using localStorage
With localStorage mocked, you can now write tests that interact with it just like you would in your app’s actual code.
describe("localStorage mock", () => {
beforeEach(() => {
localStorage.clear();
});
test("should store and retrieve a simple value", () => {
localStorage.setItem("theme", "dark");
expect(localStorage.getItem("theme")).toBe("dark");
});
test("should handle JSON data", () => {
const settings = { notifications: true };
localStorage.setItem("app-settings", JSON.stringify(settings));
const saved = JSON.parse(localStorage.getItem("app-settings") || "{}");
expect(saved.notifications).toBe(true);
});
test("should remove an item", () => {
localStorage.setItem("activeTab", "dashboard");
localStorage.removeItem("activeTab");
expect(localStorage.getItem("activeTab")).toBe(null);
});
test("should clear all items", () => {
localStorage.setItem("a", "1");
localStorage.setItem("b", "2");
localStorage.clear();
expect(localStorage.getItem("a")).toBe(null);
expect(localStorage.getItem("b")).toBe(null);
});
});
💡 Quick Reality Check: Don’t Store Sensitive Stuff
This part’s serious: don’t store sensitive data like tokens, passwords, or anything personal in localStorage
, especially outside tests.
It’s readable via browser dev tools and wide open to XSS attacks. Your tests won’t care, but real users will.
🙌 That’s It. Go Forth and Test!
Top comments (1)