How do I deal with localStorage in jest tests?

后端 未结 17 1750
长情又很酷
长情又很酷 2020-11-28 02:01

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

17条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-28 02:55

    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.

提交回复
热议问题