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

问题描述 投票:0回答:1

我正在尝试为一个函数编写单元测试,但无法弄清楚如何检查它是否使用特定参数调用嵌套函数。我假设我需要同时使用chaon和mocha的sinon,但是我真的可以使用一些帮助。

我要测试的功能如下:

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

我想测试是否在有或没有err变量的情况下调用next。从到目前为止的读物来看,我应该为此使用间谍(但是我应该如何使用)?从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/

javascript unit-testing mocha chai sinon
1个回答
0
投票

如果您具有这样的功能

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 instancef 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

© www.soinside.com 2019 - 2024. All rights reserved.