【发布时间】:2014-02-05 08:00:42
【问题描述】:
假设我有这样的功能:
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();
});
但我想要三个测试,而不是一个包含三个断言/期望的测试。
如何做到这一点?
【问题讨论】:
-
每次测试后你都恢复了模拟吗?
-
@CarlosCampderrós var obj 在 setup 函数中声明,因此在此测试中不需要恢复。
-
我不确定这个问题不仅仅是理论上的问题。您正在告诉Sinon,您希望该方法被调用 once().withExactArgs(1) 所以预期是正确的。也许这需要重构你的代码?
-
我认为您需要查看 spy.withArgs。 documentation 似乎暗示您只能监视那些带有特定参数的调用。可能有用。
-
@Sonata 我能想到的重构是将三个调用分成三个方法,然后调用这三个方法,不过希望能找到更好的选择。如果调用次数是动态的,则此系统可能会失败。
标签: javascript unit-testing sinon