TypeError:无法设置仅具有吸气剂的#<window>的属性localStorage

时间:2019-04-10 07:20:42

标签: javascript local-storage fetch-mock

我正在像unitests一样嘲笑localStorage

def english_apps(dataset):
    results = []  # Used to store all results before returning them.
    for row in dataset:
        app_name = row[0]
        for character in app_name:
            if ord(character) >= 127:
                results.append(False)
            else: 
                results.append(True)

    return results

english_apps(android_clean)
# Returns a list of booleans.

并设置localStorage之类的

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

一切正常,直到我将Node更新为window.localStorage = localStorageMock()

10.15.1引发错误。

关于如何模拟localStorage并将其设置为window.localStorage的任何想法。

P.S我在localStorage上得到了TypeError: Cannot set property localStorage of #<Window> which has only a gettersetItem之类的答案,有什么办法可以一次设置整个localStorage。

1 个答案:

答案 0 :(得分:1)

添加

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")