How to Test localStorage in React Apps: A Step-by-Step Guide (2026)

Master testing localStorage in React apps with Jest. Achieve full coverage for robust app behavior.

How to Test localStorage in React Apps: A Step-by-Step Guide (2026)

Testing localStorage in your React applications is crucial for ensuring that your app behaves correctly across different user sessions. This guide will walk you through the process of testing localStorage using Jest, with a focus on achieving full test coverage, including private routes that rely on localStorage for authentication.

Key Takeaways

  • Learn how to mock localStorage in Jest.
  • Understand the importance of testing for private routes.
  • Achieve full test coverage for lines involving localStorage.
  • Troubleshoot common issues with localStorage testing.

In React apps, localStorage is often used to store user session data, preferences, or authentication tokens. However, testing components that interact with localStorage can be challenging, especially when aiming for complete code coverage. This guide will help you understand how to effectively test components that use localStorage, ensuring your app is robust and reliable.

Prerequisites

  • A basic understanding of React and JavaScript.
  • Familiarity with Jest for testing React applications.
  • Node.js and npm installed on your machine.

Step 1: Set Up Your React Environment

Ensure you have a React project set up with Jest configured for testing. If not, create a new React project and install Jest:

npx create-react-app my-app
cd my-app
yarn add --dev jest

Configure Jest in your package.json if it's not already set up:


"scripts": {
  "test": "jest"
}

Step 2: Mock localStorage in Jest

Jest allows us to mock functions, including browser APIs such as localStorage. By mocking localStorage, we can simulate its behavior and test how our components respond to it.

Create a file setupTests.js in your src directory to configure Jest's setup:

global.localStorage = {
  getItem: jest.fn(),
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn()
};

By doing this, you ensure that every test suite has access to a mocked version of localStorage.

Step 3: Write Tests for Components Using localStorage

Assuming you have a component that uses localStorage, such as a PrivateRoute component, you can write tests to cover its logic. Here's an example:

import { render } from '@testing-library/react';
import PrivateRoute from './PrivateRoute';

describe('PrivateRoute Component', () => {
  it('redirects to login if no token is found', () => {
    localStorage.getItem.mockReturnValue(null);
    // Render your component and assert the redirection logic
    const { getByText } = render();
    expect(getByText('Please log in')).toBeInTheDocument();
  });

  it('renders the component if a token is present', () => {
    localStorage.getItem.mockReturnValue('fake-token');
    // Render your component and assert the correct rendering
    const { getByText } = render();
    expect(getByText('Welcome')).toBeInTheDocument();
  });
});

These tests check whether the PrivateRoute behaves correctly based on the presence of a token in localStorage.

Step 4: Ensure Full Coverage

To ensure that the line involving localStorage.getItem is covered, make sure your tests simulate both scenarios: when the token is absent and when it is present. This dual testing approach ensures that all possible paths of execution are tested.

Common Errors/Troubleshooting

  • Mock Implementation Not Working: Ensure that setupTests.js is correctly set up and being loaded by Jest.
  • localStorage is Undefined: Check your Jest configuration to ensure global mocks are being applied.
  • Unexpected Test Failures: Review your mock logic and ensure localStorage methods are correctly mocked.

By following this guide, you'll be able to write thorough tests for components that interact with localStorage, leading to more robust and maintainable React applications.

Frequently Asked Questions

Why mock localStorage in tests?

Mocking localStorage allows you to simulate its behavior in a controlled environment, ensuring your tests are reliable and isolated from real browser data.

How can I ensure full test coverage?

Write tests that cover all branches of your logic, including scenarios where localStorage data is present and absent.

What if my tests fail unexpectedly?

Check your Jest setup and mock implementations to ensure they are correctly configured.