This post will show you how to stub window/document properties like getElementById
and custom functions. Let’s understand this with an example. Consider the following javascript code. In this code, I am getting the div and setting the property of display
In this article, I am using Sinon stub
but in the next article, I will show you how to use sinon mock and spy
function showHideDiv() {
var div = document.getElementById("myDIV");
if (div.style.display === "none") {
div.style.display = "block";
} else {
div.style.display = "none";
}
}
Let’s write the test using mocha
and sinonjs
it("should stub dom element", () => {
var dom = sinon.stub(document, "getElementById");
const domTree = {
style: {
display: undefined
},
};
sinon.stub(domTree.style, "display").value("none");
dom.withArgs("myDIV").returns(domTree);
showHideDiv();
expect(domTree.style.display).to.be.eq("block");
});
before(function () {
const jsdom = require("jsdom");
const { window } = new jsdom.JSDOM(`...`);
global.document = window.document;
});