unit-testing - 模拟使用箭头函数作为参数调用的方法

标签 unit-testing ecmascript-6 sinon arrow-functions sinon-chai

如何使用 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/

相关文章:

python - 如何在运行 Django 测试之前加载测试 yaml 文件?

javascript - setState 在 React 中的 setInterval 中不起作用

javascript - dojo中如何加载不是模块的JS文件?

javascript - 多行函数调用的 eslint 规则

javascript - 作为参数传递的函数应该使用同一调用中的另一个参数

javascript - 在 sinon 中 stub 整个类以进行测试

javascript - 使用带有 Promise 的 sinon 进行单元测试

ruby-on-rails - Date 与 ActiveSupport::TimeWithZone 的比较失败

iOS 测试目标无法访问目标 pod

java - mock - 意外的期望 - 不知道我做错了什么