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) {
    element[0].addClass("success");
  } else {
    element[0].removeClass("failed");
  }
}
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(),
                removeClass,
            },
        ];
        jest.spyOn($.fn, "init").mockReturnValue(myObj);
        showHide();
        expect(getBoundingClientRectSpy).toBeCalled();
        expect(removeClass).toBeCalledTimes(1);
    });
});

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

إرسال تعليق

Please do not post any spam link in the comment box😊

أحدث أقدم

Blog ads

CodeGuru