Mocking `document` in jest

Similar to what others have said, but instead of trying to mock the DOM yourself, just use JSDOM: // __mocks__/client.js import { JSDOM } from “jsdom” const dom = new JSDOM() global.document = dom.window.document global.window = dom.window Then in your jest config: “setupFiles”: [ “./__mocks__/client.js” ],

How do I deal with localStorage in jest tests?

Great solution from @chiedo However, we use ES2015 syntax and I felt it was a little cleaner to write it this way. class LocalStorageMock { constructor() { this.store = {}; } clear() { this.store = {}; } getItem(key) { return this.store[key] || null; } setItem(key, value) { this.store[key] = String(value); } removeItem(key) { delete this.store[key]; … Read more