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

  • 相关阅读:
    BZOJ1941Hide and Seek
    数学与树学(娱乐向)
    树状数组(模板)
    BZOJ2716天使玩偶
    BZOJ3262陌上花开
    BZOJ3781小B的询问
    BZOJ3236作业
    Bsgs模板
    HNOI2008明明的烦恼
    BZOJ1211树的计数
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9672384.html
Copyright © 2011-2022 走看看