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

时间:2016-07-15 03:00:03

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

如何使用Sinon包来存根/模拟方法调用,其中我使用箭头函数调用其中一个参数?例如

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文档中找不到任何内容,也没有在谷歌搜索中尝试过几次。

1 个答案:

答案 0 :(得分:0)

您可以使用matchers完成您尝试做的松散匹配,以便与任何功能进行比较

objWithMethod.method

它会失败,因为y.anotherMethod()根本没有被调用。

  

//我想测试用{/ p>调用(x) => objWithMethod.method(x)      

// SUT作为参数

无法完成,因为代码并未考虑测试。 JS无法反映局部变量,{{1}}函数是黑盒子。

为了能够进行测试并获得100%的覆盖率,每个变量和闭包应该暴露给外部世界。