Mocking localStorage for TypeScript Unit Tests with Jest: A Complete Guide (2026)

Discover how to effectively mock localStorage for TypeScript unit tests using Jest in this comprehensive guide. Solve common issues and enhance your testing.

Mocking localStorage for TypeScript Unit Tests with Jest: A Complete Guide (2026)

Mocking localStorage for TypeScript Unit Tests with Jest: A Complete Guide (2026)

Unit testing is a crucial part of modern software development, ensuring that individual components of an application work as expected. When working with web applications, interactions with localStorage often need to be tested. However, developers frequently face the issue of localStorage not being defined in their tests, especially when using TypeScript and Jest. This guide will walk you through the process of effectively mocking localStorage for TypeScript unit tests using Jest.

Key Takeaways

  • Understand the importance of mocking localStorage in unit tests.
  • Learn how to set up Jest for TypeScript projects.
  • Implement a custom mock for localStorage in Jest.
  • Troubleshoot common errors related to localStorage mocking.

Mocking localStorage is essential because it allows you to simulate and test how your code interacts with the browser's storage without relying on a real browser environment. This tutorial will provide you with a robust setup for mocking localStorage, helping you write reliable tests for your TypeScript applications.

Prerequisites

  • Basic knowledge of JavaScript and TypeScript.
  • Familiarity with Jest testing framework.
  • Node.js and npm installed on your machine.
  • A TypeScript project set up with Jest.

Step 1: Set Up Your TypeScript Project

Before we mock localStorage, ensure your TypeScript project is properly set up with Jest. If you haven't already, follow these steps:

# Initialize a new Node.js project
npm init -y

# Install TypeScript
npm install typescript --save-dev

# Install Jest and its TypeScript support
npm install jest ts-jest @types/jest --save-dev

# Create a basic tsconfig.json
npx tsc --init

# Initialize Jest configuration
npx ts-jest config:init

These commands will set up a new Node.js project, install TypeScript, Jest, and configure them to work together.

Step 2: Create a localStorage Mock

To mock localStorage, create a separate file that defines the mock implementation. This allows you to easily reuse the mock across multiple test files.

// jest-localstorage-mock.ts
export const localStorageMock = {
  getItem: jest.fn((key: string) => {
    return localStorageMock.store[key] || null;
  }),
  setItem: jest.fn((key: string, value: string) => {
    localStorageMock.store[key] = value;
  }),
  removeItem: jest.fn((key: string) => {
    delete localStorageMock.store[key];
  }),
  clear: jest.fn(() => {
    localStorageMock.store = {};
  }),
  store: {} as Record
};

This mock object simulates the behavior of localStorage by using an internal store object to keep track of items.

Step 3: Integrate the Mock with Jest

Now, integrate the mock with Jest by adding it to your test setup. Create a setup file if you don't have one, and configure Jest to use it.

// jest.setup.js
import { localStorageMock } from './jest-localstorage-mock';
global.localStorage = localStorageMock;

In your package.json, ensure that Jest is set to use this setup file:


"jest": {
  "setupFilesAfterEnv": ["/jest.setup.js"]
}

This configuration makes the localStorageMock available globally in all your tests, allowing you to simulate localStorage interactions easily.

Step 4: Write Tests Using the Mock

With the mock set up, you can now write tests that involve localStorage. Here's an example that demonstrates how to test a function that uses localStorage:

// myFunction.test.ts
import { myFunction } from './myFunction';

describe('myFunction', () => {
  beforeEach(() => {
    localStorage.clear();
  });

  it('should store a value in localStorage', () => {
    myFunction('testKey', 'testValue');
    expect(localStorage.setItem).toHaveBeenCalledWith('testKey', 'testValue');
    expect(localStorage.getItem('testKey')).toBe('testValue');
  });
});

This test verifies that myFunction correctly stores a value in localStorage using the mock implementation.

Common Errors/Troubleshooting

  • ReferenceError: localStorage is not defined: Ensure that your Jest setup file correctly imports and assigns the localStorageMock to the global scope.
  • Mock functions not being called: Double-check that your mock implementation is correctly set up and that Jest is configured to use your setup file.
  • TypeScript errors: Ensure that TypeScript types are correctly imported and that your tsconfig.json file is properly configured.

By following these steps, you should have a reliable setup for mocking localStorage in your Jest tests, enabling you to write effective unit tests for your TypeScript applications.

Frequently Asked Questions

Why mock localStorage in tests?

Mocking localStorage allows you to simulate its behavior without relying on a real browser environment, ensuring tests are isolated and reliable.

How does Jest help with mocking?

Jest provides built-in functions for mocking, allowing you to replace real implementations with mock objects that simulate behavior for testing purposes.

Can I use this setup for other storage types?

Yes, you can adapt this setup to mock other storage types like sessionStorage by following similar steps and creating appropriate mock implementations.