jestjs – 如何在开玩笑测试中处理localStorage?

我一直在Jest测试中得到“localStorage is not defined”,这是有道理的,但我的选择是什么?打砖墙.
最佳答案
@chiedo的绝佳解决方案

但是,我们使用ES2015语法,我觉得用这种方式写它有点干净.

class LocalStorageMock {
  constructor() {
    this.store = {};
  }

  clear() {
    this.store = {};
  }

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

  setItem(key, value) {
    this.store[key] = value.toString();
  }

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

global.localStorage = new LocalStorageMock;

转载注明原文:jestjs – 如何在开玩笑测试中处理localStorage? - 代码日志