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” ],

Test process.env with Jest

The way I did it can be found in this Stack Overflow question. It is important to use resetModules before each test and then dynamically import the module inside the test: describe(‘environmental variables’, () => { const OLD_ENV = process.env; beforeEach(() => { jest.resetModules() // Most important – it clears the cache process.env = { …OLD_ENV … Read more

Jest: Timer and Promise don’t work well. (setTimeout and async function)

Yes, you’re on the right track. What happens await simpleTimer(callback) will wait for the Promise returned by simpleTimer() to resolve so callback() gets called the first time and setTimeout() also gets called. jest.useFakeTimers() replaced setTimeout() with a mock so the mock records that it was called with [ () => { simpleTimer(callback) }, 1000 ]. … Read more

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