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

  • 相关阅读:
    19. vue的原理
    18.jwt加密
    17.vue移动端项目二
    16.vue-cli跨域,swiper,移动端项目
    15.vue动画& vuex
    14.vue路由&脚手架
    13.vue组件
    12.vue属性.监听.组件
    11.vue 数据交互
    从尾到头打印链表
  • 原文地址:https://www.cnblogs.com/Answer1215/p/9672384.html
Copyright © 2011-2022 走看看