Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Jest mock localStorage #test #jest
// ./__mocks__/localStorage.js
let mockStorage = {};
module.exports = window.localStorage = {
setItem: (key, val) => Object.assign(mockStorage, {[key]: val}),
getItem: (key) => mockStorage[key],
clear: () => mockStorage = {}
};
// Then import it in the reducer test file
import '../__mocks__/localStorage';
@jandersonTIC

This comment has been minimized.

Copy link

@jandersonTIC jandersonTIC commented Feb 8, 2018

It worked! Thanks.

@nikhilSriva

This comment has been minimized.

Copy link

@nikhilSriva nikhilSriva commented Jun 26, 2018

Hey, can you give me a little insight on the usage? Like in the .test.js file, do we have to initialize anything or code something?

@roppa

This comment has been minimized.

Copy link

@roppa roppa commented Jun 26, 2018

@krey3ix line 11 has instructions. Just import it like import '../__mocks__/localStorage'; and it sets window.localStorage automatically. I guess you could do something like:

let mockStorage = {};

const localStorage = {
  setItem: (key, val) => Object.assign(mockStorage, {
    [key]: val
  }),
  getItem: (key) => mockStorage[key],
  clear: () => mockStorage = {}
};

export default localStorage;

Then

const localStorage = import '../__mocks__/localStorage';
global.localStorage = localStorage;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment