How to mock jQuery selector and return HTML element using JEST

When you have DOM dependency in your javascript application, you can easily mock the dom elements and return the HTML element.

Consider the following code snippet for this example. The CSS class is added and removed based on the element’s position. To put this code to the test, we must mock the JQuery selector and return a mock document with the required property and event.

const $ = require("jquery");
function showHide() {
  let element = $("#test");
  const top = element[0].getBoundingClientRect().top;
  if (top >= 100) {
  } else {
module.exports = { showHide };

describe("JQuery Selector", () => {
    it("should call $.init and return mock version of document", ()
        => {
        const getBoundingClientRectSpy = jest.fn(() => ({ top: 10 }));
        const removeClass = jest.fn();
        var myObj = [
                name: "test",
                getBoundingClientRect: getBoundingClientRectSpy,
                addClass: jest.fn(),
        jest.spyOn($.fn, "init").mockReturnValue(myObj);

Note: when we call $(”#someid”) jquery call the “init” method. {alertInfo}

The above technique can be used for the following scenario also

  • Mock getElementById or document.getElementById
  • Mock HTML element
Next Post Previous Post
No Comment
Add Comment
comment url