Advanced Sinon tutorial- Mocks, Spies & Stubs

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 ( === "none") { = "block";
  } else { = "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(, "display").value("none");

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 JSDOM npm package.
Once it is installed, write the following code inside before and 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;

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

Post a Comment (0)
Previous Post Next Post