gpt4 book ai didi

unit-testing - 使用 sinon 断言使用所需参数进行了特定的 stub 调用

转载 作者:行者123 更新时间:2023-12-03 00:24:24 28 4
gpt4 key购买 nike

假设您正在测试一个函数,该函数将使用不同的参数多次调用依赖项:

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.usedWith 这样的断言?

this fiddle中的示例设置

最佳答案

正如我创建示例 fiddle 一样,我找到了解决方案......

在我的代码中,我使用的是Sinon 1.7.1版本,但是在使用Sinon的最新版本(截至今天的1.14.1)编写 fiddle 时,我刚刚意识到您可以将特定的spyCall传递给断言。 CalledWith 方法。这意味着您可以编写以下内容:

sinon.assert.calledWith(dependencyStub.firstCall, "a", 1);
sinon.assert.calledWith(dependencyStub.secondCall, "b", 2);

所以我想创建的测试可以很好地编写:

test("dependency was called multiple times as expected - with order", function () {
var dependencyStub = sinon.stub();

sut.ImportantFunction(dependencyStub);

sinon.assert.calledTwice(dependencyStub);
sinon.assert.calledWith(dependencyStub.firstCall, "a", 1);
sinon.assert.calledWith(dependencyStub.secondCall, "b", 2);
});

fiddle here

编辑

在github存储库中找到the discussion导致了这一变化。 到更改合并到主版本的日期,这应该适用于版本 1.13.0 及更高版本。

如果您使用的是旧版本,您可以使用 mantoni 的解决方案:

test("dependency was called multiple times as expected with order - pre 1.13.0", function () {
var dependencyStub = sinon.stub();

sut.ImportantFunction(dependencyStub);

sinon.assert.calledTwice(dependencyStub);
sinon.assert.callOrder(
dependencyStub.withArgs("a", 1),
dependencyStub.withArgs("b", 2));
});

关于unit-testing - 使用 sinon 断言使用所需参数进行了特定的 stub 调用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29899656/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com