如何正确存根函数 return 值?

How to properly stub a function return value?


我正在尝试模拟 class 方法的 return 值并不断收到此错误:

not ok Unsatisfied verification on test double. Wanted: - called with (true). But there were no invocations of the test double.

这是我的测试代码:

// Imports for unit testing
const tap = require('tap');
const Subject = require('../src/iTunesClient.js');
const td = require('testdouble');

let reqJson;

// Ensure the iTunes class methods are called
tap.test('iTunesClient class methods function as intended', (t) => {
  t.beforeEach((ready) => {
    reqJson = td.replace('../src/reqJson.js');
    ready();
  });

  t.afterEach((ready) => {
    td.reset();
    ready();
  });

  t.test('iTunesClient.getData', (assert) => {
    const callback = td.function();
    const subject = new Subject();
    subject.setTerm('abc 123');
    subject.setURL();

    td.when(reqJson.get(td.callback)).thenCallback(true);

    subject.getData(callback);

    td.verify(callback(true));
    assert.end();
  });

  t.end();
});

具体来说,这一行与我的问题有关:

td.verify(callback(true));

如何为reqJson.get()伪造true的回调值?现在,Subject.geData()iTunesClient class 的一个方法,它调用另一个文件 reqJson.js,以使用其导出的 get() 方法。

从您的示例中很难判断,但看起来您在调用 td.replace 之前需要 iTunesClient。在这种情况下,将需要真正的 reqJson 模块并将其缓存在第 3 行。

您需要尽早致电 td.replace 以避免这种情况,例如在要求 tapiTunesClient.

之间

我想更新这个问题,因为我最近解决了这个问题。本质上,我有两个问题:

  1. 考虑到两个 reqJson 函数参数
  2. 考虑所有回调 return 值

根据 testdouble documentation 的第 1 项:

When passed td.matchers.anything(), any invocation of that test double function will ignore that parameter when determining whether an invocation satisfies the stubbing.

因此,我调整了我的代码行如下:

之前: td.when(reqJson.get(td.callback)).thenCallback(true);

之后: td.when(reqJson.get(td.matchers.anything(), td.callback)).thenCallback(null, null, null);