Javascript 测试 - 使用特定参数调用的函数

Javascript testing - function called with specfic argument

我正在尝试为函数编写单元测试,但不知道如何检查它是否使用特定参数调用嵌套函数。我假设为此我需要将 sinon 与 chai 和 mocha 一起使用,但我真的需要一些帮助。

我想测试的函数如下所示:

function myFunc(next, value) {
    if (value === 1) {
      const err = new Error('This sets an error');
      next(err);
    } else {
      next();
    }
}

我想测试 next 是否在有或没有 err 变量的情况下被调用。从目前我读到的内容来看,我应该为此使用间谍(我认为),但我将如何使用该间谍?从 Sinon 文档看这个例子,我不清楚 PubSub 来自哪里:

"test should call subscribers with message as first argument" : function () {
    var message = "an example message";
    var spy = sinon.spy();

    PubSub.subscribe(message, spy);
    PubSub.publishSync(message, "some payload");

    sinon.assert.calledOnce(spy);
    sinon.assert.calledWith(spy, message);
}

来源:https://sinonjs.org/releases/latest/assertions/

如果你有这样的功能

function myFunc(next, value) {
    if (value === 1) {
      const err = new Error('This sets an error');
      next(err);
    } else {
      next();
    }
}

测试可能看起来像这样

it ('should call the callback with an Error argument', function (done) {

    const callback = (err) => {

        if (err && err instanceof Error && err.message === 'This sets an error'){
            // test passed, called with an Error arg
            done();
        } else {
            // force fail the test, the `err` is not what we expect it to be
            done(new Error('Assertion failed'));
        }
    }

    // with second arg equal to `1`, it should call `callback` with an Error
    myFunc(callback, 1);
});

所以你不一定需要 sinon