samedi 20 juin 2020

Jest unable to load setupFiles

Goal: To mock local storage in for testing in Jest.

Problem: Jest could not load the localStorage mock file, I am getting setItem is undefined since its the localStorage is not defined according to Jest.

However, I can bypass this problem by simply importing it to each and every test file but that seems very hectic and not optimal. Please help me so I can make this code better.

I have created react app using create-react-app

if (!window.localStorage) {
    window.localStorage = {}
    Object.assign(window.localStorage, {
      removeItem: function removeItem(key) {
        delete this[key]
      }.bind(window.localStorage),
      setItem: function setItem(key, val) {
        this[key] = String(val)
      }.bind(window.localStorage),
      getItem: function getItem(key) {
        return this[key]
      }.bind(window.localStorage),
    })
  }

Here is the package.json file where it has the Jest configuration.

"jest": {
  "setupFiles": [
    "jest-canvas-mock",
    "./test/setup-test-framework"
  ]
}

Aucun commentaire:

Enregistrer un commentaire