zoukankan      html  css  js  c++  java
  • [Unit Testing] Unit Test a Function that Invokes a Callback with a Sinon Spy

    Unit testing functions that invoke callbacks can require a lot of setup code. Using sinon.spy to create a fake callback function can simplify your unit tests while still allowing you to observe the output of the function you're testing.

    const fs = require("fs");
    const assert = require("assert");
    const sinon = require("sinon");
    const jQuery = require("jQuery");
    
    function getTempFiles(callback) {
      const contents = fs.readdirSync("/tmp");
      return callback(contents);
    }
    
    describe("getTempFiles", () => {
      it("should call the provided callback", () => {
        const spy = sinon.spy();
        getTempFiles(spy);
        assert.equal(spy.callCount, 1);
        assert.ok(spy.getCall(0).args[0] instanceof Array);
      });
    
      it("should call the function with correct args", () => {
        var object = { method: function() {} };
        var spy = sinon.spy(object, "method");
        object.method(42);
        object.method(1);
        assert.ok(spy.withArgs(42).calledOnce);
        assert.ok(spy.withArgs(1).calledOnce);
      });
    
      it("should wrap a existing method", () => {
        sinon.spy(jQuery, "ajax");
        jQuery.getJSON("/some/resource");
        assert.ok(jQuery.ajax.calledOnce);
      });
    });

    Docs

  • 相关阅读:
    luogu P4009 汽车加油行驶问题
    luogu P4015 运输问题
    luogu P2763 试题库问题
    luogu P4011 孤岛营救问题
    luogu P2765 魔术球问题
    linux 网卡
    linux yum错误
    ubuntu登录备注信息
    Ubuntu网卡配置
    linux 走三层内网添加静态路由
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9672384.html
Copyright © 2011-2022 走看看