5

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 = () => {
     return Promise.resolve(JSON.parse(localStorage.getItem('cache')));
   }
}

sample.test.js

import { mount } from 'enzyme';
import React from 'react';
import Component from '../Component';

const cacheData = JSON.stringify(require('../__mock__/data.json'));

// Trying to mock the function causing error _Cache.default .....
jest.mock('./Cache', () => {
  return jest.fn().mockImplementation(() => {
    return {
      getCache: () => Promise.resolve(),
    }
  })
});

beforeAll(() => {
  localStorage.setItem('cache', cacheDate);
});

describe("<Component /> ", () => {
   it('set data to state', () => {
       const wrapper = mount(<Component />);
       wrapper.instance().getCache(); <-- my function in <Component /> to get data from cache service
       wrapper.update();

      console.log(wrapper.state()) <---- return null
   })
})

in <Component /> componentDidMound cycle called the cache service to load the cache, and here I expecting the data getting from localStorage in the test. I have been trying another way to do this but nothing is working for me

skyboyer
  • 22,209
  • 7
  • 57
  • 64
Darmawan Z.
  • 411
  • 8
  • 20
  • I have been test for simple setItem and directly getitem in data was added to localStorage. so maybe the problem is how to mocking the Cache service and make Component called it getCache function – Darmawan Z. Sep 03 '20 at 06:36
  • *Trying to mock the function causing error _Cache.default* - what exactly is the error? `localStorage.setItem('cache', cacheDate)` - this doesn't help because you already stubbed it, it's a no-op. Either don't replace existing localStorage implementation (Jest JSDOM provides one), or mock it in a way that will work with yours, `localStorage.getItem.mockReturnValue(...)`. – Estus Flask Sep 03 '20 at 11:15
  • yes the solution i am used is try to manual mocking the cache service and the data was exists. SOLVED – Darmawan Z. Sep 07 '20 at 04:00

0 Answers0