How do I deal with localStorage in jest tests?

2019-01-12 20:56发布

I keep getting "localStorage is not defined" in Jest tests which makes sense but what are my options? Hitting brick walls.

标签: jestjs
8条回答
Fickle 薄情
2楼-- · 2019-01-12 21:38

Riffed off some other answers here to solve it for a project with Typescript. I created a LocalStorageMock like this:

export class LocalStorageMock {

    private store = {}

    clear() {
        this.store = {}
    }

    getItem(key: string) {
        return this.store[key] || null
    }

    setItem(key: string, value: string) {
        this.store[key] = value
    }

    removeItem(key: string) {
        delete this.store[key]
    }
}

Then I created a LocalStorageWrapper class that I use for all access to local storage in the app instead of directly accessing the global local storage variable. Made it easy to set the mock in the wrapper for tests.

查看更多
ら.Afraid
3楼-- · 2019-01-12 21:38

As @ck4 suggested documentation has clear explanation for using localStorage in jest. However the mock functions were failing to execute any of the localStorage methods.

Below is the detailed example of my react component which make uses of abstract methods for writing and reading data,

//file: storage.js
const key = 'ABC';
export function readFromStore (){
    return JSON.parse(localStorage.getItem(key));
}
export function saveToStore (value) {
    localStorage.setItem(key, JSON.stringify(value));
}

export default { readFromStore, saveToStore };

Error:

TypeError: _setupLocalStorage2.default.setItem is not a function

Fix:
Add below mock function for jest (path: .jest/mocks/setUpStore.js )

let mockStorage = {};

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

Snippet is referenced from here

查看更多
登录 后发表回答