How do I deal with localStorage in jest tests?

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

    The following solution is compatible for testing with stricter TypeScript, ESLint, TSLint, and Prettier config: { "proseWrap": "always", "semi": false, "singleQuote": true, "trailingComma": "es5" }:

    class LocalStorageMock {
      public store: {
        [key: string]: string
      }
      constructor() {
        this.store = {}
      }
    
      public clear() {
        this.store = {}
      }
    
      public getItem(key: string) {
        return this.store[key] || undefined
      }
    
      public setItem(key: string, value: string) {
        this.store[key] = value.toString()
      }
    
      public removeItem(key: string) {
        delete this.store[key]
      }
    }
    /* tslint:disable-next-line:no-any */
    ;(global as any).localStorage = new LocalStorageMock()
    

    HT/ https://stackoverflow.com/a/51583401/101290 for how to update global.localStorage

提交回复
热议问题