TypeError: Cannot set property localStorage of #<Window> which has only a getter
Asked Answered
B

1

5

I am mocking localStorage in unitests like

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

and setting localStorage like

window.localStorage = localStorageMock()

It was working fine until, I have updated Node to 10.15.1.

It is throwing error that TypeError: Cannot set property localStorage of #<Window> which has only a getter.

Any idea that how I can mock localStorage and set it to window.localStorage.

P.S I am getting answers like setItem and getItem on localStorage, is there any way that I can set whole localStorage at once.

Benito answered 10/4, 2019 at 7:20 Comment(2)
I met same issue with 10.16.3. Still not solved. Any update of your question?Lani
I got this after upgrading to jsdom 16.4.0 and node 14.13.0Titter
W
8

Add

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

Full example:

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")
Wallie answered 16/11, 2020 at 18:58 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.