简体   繁体   中英

Mock Jquery event using Sinon.js

I have the following javascript module which when the user clicks on back to top button it animates and move the page to the top.

    const jsdom = require("jsdom");
    const { JSDOM } = jsdom;
    const { window } = new JSDOM(`...`);
    var $ = require("jquery")(window);
    
    const BackToTop = (function () {
      var baclTop = () => {
        $(".back").on("click", BackToTop.animate);
      };
      var animate = function () {
        $("html, body").animate({ scrollTop: "0" }, 1000);
      };
    
      return {
        baclTop,
        animate,
      };
    })();
    
    module.exports = BackToTop;

I have written the following test case using mocha and sinon.js but I am getting the following error

const BackToTop = require("../src/backToTop");
const sinon = require("sinon");
const jsdom = require("jsdom");
const document = new jsdom.JSDOM("<html></html>", {});
const window = document.defaultView;
global.document = document;
global.window = window;
const { expect } = require("chai");

describe("Name of the group", () => {
  it("should ", (done) => {
    $("body").append("<div class='sd-back-to-top'>hello world</div>");
    const operation = sinon.spy(BackToTop, "animate");

    $(".back").trigger('click');
    BackToTop.baclTop();
    expect(operation.callCount).to.be.eq(1);
    done();
  });
});
AssertionError: expected 0 to equal 1
    at Context.<anonymous> (test\backToTop.spec.js:17:39)
    at processImmediate (internal/timers.js:461:21)

+ expected - actual

-0
+1

I have already tried a lot of articles but no luck

Thanks in advance!

The BackToTop module has two private (scoped) functions: baclTop and animate .

When you expose them, you are declaring another two function attached to the module:

return {
    baclTop, // shortcut for baclTop: baclTop
    animate,
}

So when you create the spy, sinon will wrap the function exposed function in the return bock:

const operation = sinon.spy(BackToTop, "animate");

But, whe you call BackToTop.baclTop() this will call the "internal" version of the animate function, and sinon can't intercept this call.

You can't do that, you must rewrite your code in a testable way, or just spy only functions that you call directly.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM