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");
});
If you run the above test, it will give you an error that the document is undefined. Because our testing is running in a node.js environment which does not support document. To test this, we have to install
JSDOMnpm package.
Once it is installed, write the following code insidebeforeand then run the test. This time it will pass.{alertError}
before(function () {
const jsdom = require("jsdom");
const { window } = new jsdom.JSDOM(`...`);
global.document = window.document;
});