How do I deal with localStorage in jest tests?

后端 未结 17 1793
长情又很酷
长情又很酷 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:45

    A better alternative which handles undefined values (it doesn't have toString()) and returns null if value doesn't exist. Tested this with react v15, redux and redux-auth-wrapper

    class LocalStorageMock {
      constructor() {
        this.store = {}
      }
    
      clear() {
        this.store = {}
      }
    
      getItem(key) {
        return this.store[key] || null
      }
    
      setItem(key, value) {
        this.store[key] = value
      }
    
      removeItem(key) {
        delete this.store[key]
      }
    }
    
    global.localStorage = new LocalStorageMock
    

提交回复
热议问题