【问题标题】:Mocking a method which is called using an arrow function as a parameter模拟使用箭头函数作为参数调用的方法
【发布时间】:2016-11-18 03:20:40
【问题描述】:

如何使用 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 文档中也找不到任何东西,在谷歌搜索几次尝试后也找不到。

【问题讨论】:

  • 您没有在代码中访问objWithMethod.methodobjWithMethod 是一个对象,而您将其称为函数。它是如何工作的?
  • 您的代码导致VM604:5 Uncaught TypeError: objWithMethod is not a function(在您修复了第一行中额外的; 的问题后)
  • 你说得对,我的例子没有正确代表我要更新的内容
  • 更新以反映我的意思
  • 即使在更新之后 - 您也不会在代码中调用 objWithMethod.method

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


【解决方案1】:

您可以使用matchers 进行松散匹配,以便与它应该使用的任何函数进行比较

mockObj.expects('method').withArgs(sinon.match.func)

它会失败,因为objWithMethod.method 根本没有被调用。

这个

// 我想测试y.anotherMethod() 是否被调用

//(x) => objWithMethod.method(x)作为参数

无法完成,因为编写代码时没有考虑到测试。 JS不能反映局部变量,SUT函数是个黑盒。

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-03
    • 2018-02-06
    • 1970-01-01
    • 1970-01-01
    • 2022-08-23
    • 2016-06-09
    • 2018-12-13
    相关资源
    最近更新 更多