如何使用 Sinon 包 stub /模拟方法调用,其中我必须模拟的参数之一是使用箭头函数调用的?例如
let objWithMethod = { method : function(x) {}; };
function SUT() {
// use case
let x = 'some value';
let y = { anotherMethod : function(func) {}; };
// I want to test that `y.anotherMethod()` is called with
// `(x) => objWithMethod.method(x)` as the argument
y.anotherMethod((x) => objWithMethod.method(x));
}
let mockObj = sinon.mock(objWithMethod);
// Both of these fail with a "never called" error
mockObj.expects('method').once().withArgs(objWithMethod.method.bind(this, x));
mockObj.expects('method').once().withArgs((x) => objWithMethod.method(x));
SUT();
mockObj.verify();
我在 sinon 文档中找不到任何东西,也没有在尝试谷歌搜索后找到任何东西。
最佳答案
您尝试进行的松散匹配可以使用 matchers 来完成, 与它应该是的任何功能进行比较
mockObj.expects('method').withArgs(sinon.match.func)
它会失败,因为根本没有调用 objWithMethod.method
。
这个
// I want to test that
y.anotherMethod()
is called with//
(x) => objWithMethod.method(x)
as the argument
无法完成,因为编写代码时并未考虑测试。 JS不能反射(reflect)局部变量,SUT
函数是一个黑盒。
为了测试可达并获得 100% 的覆盖率,每个变量和闭包都应该暴露给外部世界。
关于unit-testing - 模拟使用箭头函数作为参数调用的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38387222/