类型错误:无法设置属性 localStorage of # 只有一个<Window> getter



我在 unitests 中嘲笑本地存储,例如

function storageMock() {
    var storage = {};
    ....
}

并设置本地存储,例如

window.localStorage = localStorageMock()

它工作正常,直到我已将节点更新为 10.15.1 .

抛出错误TypeError: Cannot set property localStorage of #<Window> which has only a getter.

任何想法,我如何模拟本地存储并将其设置为window.localStorage。

附言我在 localStorage 上得到了setItemgetItem这样的答案,有什么方法可以一次设置整个 localStorage。

添加

Object.defineProperty(window, 'localStorage', {
  value: storageMock
});

完整示例:

const localStorageMock = (() => {
  let store = {};
  return {
    getItem(key) {
      return store[key] || null;
    },
    setItem(key, value) {
      store[key] = value.toString();
    },
    removeItem(key) {
      delete store[key];
    },
    clear() {
      store = {};
    }
  };
})();
Object.defineProperty(window, 'localStorage', {
  value: localStorageMock
});
window.localStorage.setItem("KEY", "INPUT")

相关内容

  • 没有找到相关文章

最新更新