Skip to content

Unit Testing #9

Answered by ZikaZaki
RubyStack asked this question in Q&A
Sep 4, 2022 · 1 comments · 2 replies
Discussion options

You must be logged in to vote

Hi @RubyStack,
In fact, the Jest library does not support calls to localStorage. It is not a browser and doesn't implement localStorage.

The solution is to mock your own fake localStorage support like below:

browserMocks.js

const localStorageMock = (function() {
  let store = {}

  return {
    getItem: function(key) {
      return store[key] || null
    },
    setItem: function(key, value) {
      store[key] = value.toString()
    },
    removeItem: function(key) {
      delete store[key]
    },
    clear: function() {
      store = {}
    }
  }
})()

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

Replies: 1 comment 2 replies

Comment options

You must be logged in to vote
2 replies
@RubyStack
Comment options

RubyStack Sep 4, 2022
Collaborator Author

@ZikaZaki
Comment options

Answer selected by RubyStack
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants