Coding With Fun
Home Docker Django Node.js Articles Python pip guide FAQ Policy

How to mock the dom in jestjs using jsdom?


Asked by Mira Moyer on Dec 06, 2021 FAQ



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
Thereof,
Jest ships with jsdom which simulates a DOM environment as if you were in the browser. This means that every DOM API that we call can be observed in the same way it would be observed in a browser! We are mocking fetchCurrentUser.js so that our test doesn't make a real network request but instead resolves to mock data locally.
Similarly, The function being tested adds an event listener on the #button DOM element, so we need to set up our DOM correctly for the test. Jest ships with jsdom which simulates a DOM environment as if you were in the browser.
Also Know,
Given that Jest depends on Node-specific APIs and therefore only runs in Node, you can’t use Jest also. To be able to run your tests in Jest, instead of running your tests within the browser, you can bring browser APIs to Node by using JSDOM.
Indeed,
To be able to run your tests in Jest, instead of running your tests within the browser, you can bring browser APIs to Node by using JSDOM. You can think of JSDOM as an implementation of the browser environment which can run within Node. It implements web standards using pure JavaScript.