DEV Community

Darmawan Zulkifli
Darmawan Zulkifli

Posted on

2 1

Setup localStorage for testing React with jest

How to deal with localStorage in React testing using jest.

I have been added to setupTest.js

const localStorageMock = {
  getItem: jest.fn()
  setItem: jest.fn(),
  removeItem: jest.fn(),
  clear: jest.fn(),
};

global.localStorage = localStorageMock;

Here's example of my service to get cache:

export default class Cache {
   getCache = () => {

Top comments (0)

Sentry image

Make it make sense

Only the context you need to fix your broken code with Sentry.

Start debugging →

👋 Kindness is contagious

Dive into this thoughtful article, cherished within the supportive DEV Community. Coders of every background are encouraged to share and grow our collective expertise.

A genuine "thank you" can brighten someone’s day—drop your appreciation in the comments below!

On DEV, sharing knowledge smooths our journey and strengthens our community bonds. Found value here? A quick thank you to the author makes a big difference.

Okay