Skip to content

Instantly share code, notes, and snippets.

@FDiskas
Last active August 24, 2017 07:18
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save FDiskas/215a1d4ae7ac6c338514a0ca82cbbcfc to your computer and use it in GitHub Desktop.
Save FDiskas/215a1d4ae7ac6c338514a0ca82cbbcfc to your computer and use it in GitHub Desktop.
localStorage polyfill for jest #jest #localStorage

localStorage for jest

Edit jor package.json and add

"setupFiles": [
      "<rootDir>/MYPATH/polyfills.js"
],

Your test file should look like

describe(Component.name, () => {
    it('should save to localStorage', () => {
        const KEY = 'foo';
        const VALUE = 'bar';
        localStorage.setItem(KEY, VALUE);
        // Or localStorage[KEY] = VALUE;
        expect(localStorage.getItem(KEY)).toBe(VALUE);
    });
});
global.localStorage = {
getItem(key) {
return this[key];
},
setItem(key, value) {
this[key] = value;
},
removeItem(key) {
delete this[key];
},
get(key) {
return this[key];
},
set(key, value) {
this[key] = value;
},
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment