Skip to content

Provide a way to specify test environment setup file for Jest #545

Closed
@gaelollivier

Description

@gaelollivier

My App is using localStorage but when I run tests, I get this error:

ReferenceError: localStorage is not defined

Should we provide a polyfill to be able to mock it with Jest ?

Workaround

Add a --setupTestFrameworkScriptFile ./localStoragePolyfill.js to the test command in package.json, where ./localStoragePolyfill looks like this:

const localStorageMock = (() => {
  let store = {}
  return {
    getItem(key) {
      return store[key]
    },
    setItem(key, value) {
      store[key] = value.toString()
    },
    clear() {
      store = {}
    }
  };
})()

global.localStorage = localStorageMock

I guess it should be added to config/polyfills.js.

I can PR if that's fine. Not sure if we should use a simple inline polyfill or use something like node-localstorage though.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions