[Unit Testing] Unit Test a Function that Invokes a Callback with a Sinon Spy

时间:2022-01-12 15:55:10

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