【问题标题】:How to test a privately-scoped or anonymous function?如何测试私有范围或匿名函数?
【发布时间】:2021-01-08 22:50:57
【问题描述】:

假设我有以下模块:

foo.js

module.exports = function (x, f) {
  f(x);
};

bar.js

const foo = require('./foo');

module.exports = function () {
  foo(40, n => n + 2);
  //      ^
  //      f — How can I test this lambda?
};

我只需要断言当bar被调用时,foo被调用完全如上所示^

我可以测试foo 已被40 调用如下:

const td = require('testdouble');
const foo = td.replace('./foo');
const bar = require('./bar');

bar();

td.verify(foo(40, td.matchers.anything())); // Pass

但是我如何验证函数f 是一个接受一个数字,加2 并返回结果的函数?

PS:我非常清楚这并不是在测试最佳实践 101。如果我有机会以不同的方式做事,我宁愿不以这种方式进行测试。所以请幽默我。

【问题讨论】:

    标签: javascript unit-testing testdoublejs


    【解决方案1】:

    我找到了两种方法:

    td.matchers.argThat

    此匹配器采用一个谓词,该谓词采用其位置参数的值:

    const td = require('testdouble');
    const foo = td.replace('./foo');
    const bar = require('./bar');
    
    bar();
    
    td.verify(foo(40, td.matchers.argThat(f => f(40) === 42))); // Pass
    

    td.matchers.captor

    有一个称为captor 的特殊匹配器,它捕获其位置参数,并在以后通过匹配器的.value 属性使其可用:

    const tap = require('tap');
    const td = require('testdouble');
    const foo = td.replace('./foo');
    const bar = require('./bar');
    const f = td.matchers.captor();
    
    bar();
    
    td.verify(foo(40, f.capture()));
    
    tap.equal(f.value(40), 42); // Pass
    tap.equal(f.value(50), 52); // Pass
    tap.equal(f.value(60), 62); // Pass
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-04
      • 2011-02-13
      • 2011-10-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多