gpt4 book ai didi

javascript - 如何测试对具有不同参数的同一函数的多次调用?

转载 作者:可可西里 更新时间:2023-11-01 01:19:39 24 4
gpt4 key购买 nike

假设我有这样一个函数:

function foo () {
obj.method(1);
obj.method(2);
obj.method(3);
}

为了测试它,我想做 3 个测试(使用 Mocha TDD 和 Sinon):

test('medthod is called with 1', function () {
var expectation = sinon.mock(obj).expects('method').once().withExactArgs(1);
foo();
expectation.verify();
});

test('medthod is called with 2', function () {
var expectation = sinon.mock(obj).expects('method').once().withExactArgs(2);
foo();
expectation.verify();
});

test('medthod is called with 3', function () {
var expectation = sinon.mock(obj).expects('method').once().withExactArgs(3);
foo();
expectation.verify();
});

使用此系统 sinon 失败,并在每次测试时出现“意外调用”消息。

我已经解决了将树测试合二为一的问题:

test('medthod is called with 1, 2 and 3', function () {
var mock = sinon.mock(obj);
mock.expects('method').once().withExactArgs(1);
mock.expects('method').once().withExactArgs(2);
mock.expects('method').once().withExactArgs(3);
foo();
mock.verify();
});

但我想进行三个测试,而不是一个包含三个断言/期望的测试。

如何实现?

最佳答案

一如既往,当测试出现异常时,问题出在被测试的代码中

在这种情况下,我们会遇到耦合问题。目前该功能有两个职责:

  • 决定要使用的数据。
  • 用数据调用方法。

为了解决这个问题,我们必须将职责划分为两个函数/对象/类,然后分别测试每一个。例如,一种可能是:

  • 将对第一个函数(生成并返回数据的函数)进行测试,以检查返回的数据是否符合我们的预期。

  • 第二个函数(我们的原始函数)将进行一个测试,检查它是否调用数据生成器,然后进行一个测试,检查它是否将数据正确发送到预期的函数,第三个函数检查它是否调用函数数据需要多少次。

代码应该是这样的:

function foo() {
dataGenerator.generate().forEach(function (item) {
obj.method(item);
})
}

dataGenerator.generate = function () {
return [1,2,3];
};

和测试:

test('generateData is called', function () {
var expectation = sinon.mock(dataGenerator).expects('generate').once();
foo();
expectation.verify();
});

test('method is called with the correct args', function () {
var expectedArgs = 1;
sinon.stub(dataGenerator, "generate").returns([expectedArgs]);
var expectation = sinon.mock(obj).expects('method').once().withExactArgs(expectedArgs);
foo();
expectation.verify();
});

test('method is called as many times as the amount of data', function () {
sinon.stub(dataGenerator, "generate").returns([1,2]);
var expectation = sinon.mock(obj).expects('method').twice();
foo();
expectation.verify();
});

test('dataGenerator.generate returns [1,2,3]', function () {
var expected = [1,2,3];
var result = dataGenerator.generate();
assert.equal(result, expected)
});

请注意,第三个测试仅检查调用方法的次数。第二个测试已经检查数据是否正确传递,第四个测试数据本身。

关于javascript - 如何测试对具有不同参数的同一函数的多次调用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21161340/

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