【发布时间】:2015-07-06 03:17:33
【问题描述】:
假设您正在测试一个函数,该函数将使用不同的参数多次调用依赖项:
var sut = {
ImportantFunction: function(dependency){
dependency("a", 1);
dependency("b", 2);
}
};
使用 QUnit + Sinon 并假设调用的顺序并不重要,我可以编写以下测试来确保函数按预期调用依赖项:
test("dependency was called as expected", function () {
var dependencyStub = sinon.stub();
sut.ImportantFunction(dependencyStub);
ok(dependencyStub.calledTwice, "dependency was called twice");
sinon.assert.calledWith(dependencyStub, "a", 1);
sinon.assert.calledWith(dependencyStub, "b", 2);
});
但是如果顺序很重要并且我希望测试考虑到它怎么办?使用 QUnit+Sinon 编写此类测试的最佳方法是什么?
我使用了以下方法,但我丢失了sinon assertions 提供的描述性失败消息(显示预期值和实际值)。为此,我刚刚手动添加了一些描述性消息,但它不如具有预期值和实际值的失败消息有用(并且必须手动维护)。
ok(dependencyStub.firstCall.calledWith("a", 1), "dependency called with expected args 'a', 1");
ok(dependencyStub.secondCall.calledWith("b", 2), "dependency called with expected args 'b', 2");
有没有一种方法可以将sinon.assert.calledWith 之类的断言用于第一次或第二次调用等特定调用?
this fiddle 中的示例设置
【问题讨论】:
标签: unit-testing qunit sinon