Setup localStorage for testing React with jest

Viewed 2668

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

0 Answers
Related