[Unit Testing] Unit Test a Function that Invokes a Callback with a Sinon Spy
2024-09-08 16:25:48
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);
});
});
最新文章
- Tomcat源码导入eclipse的步骤
- 我是如何反编译D-Link路由器固件程序并发现它的后门的
- SQLServer的学习场景(关于row_number()和COALESCE()的使用)
- Win8.1RTM英文版安装中文语言包的两种方法
- (转)高性能网站架构之缓存篇—Redis集群搭建
- FreeMarker的教程
- Hibernate之jpa实体映射的三种继承关系
- windows上自动设置java环境变量的脚本
- Sql Server来龙去脉系列之四 数据库和文件
- SQL效率低下原因主要有
- 工作中遇到的浏览器差别(就不叫IE6bug了)
- twemproxy接收流程探索——twemproxy代码分析正编
- 基于Spark的用户行为路径分析
- flask中jinjia2模板引擎详解4
- 关于String的一些基础小题目
- put your hands up PHPLFI +CVE
- python使用redis
- 洛谷P4281 紧急集合 / 聚会
- hdu3038How Many Answers Are Wrong(带权并查集)
- WPF命令(Command)介绍、命令和数据绑定集成应用