【问题标题】:Javascript testing - function called with specfic argumentJavascript 测试 - 使用特定参数调用的函数
【发布时间】:2019-10-30 13:07:40
【问题描述】:

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

我想测试的功能如下:

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.js chai sinon


【解决方案1】:

如果你有这样的功能

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-10-24
    • 2020-10-14
    • 2014-02-14
    • 2018-04-10
    • 2018-04-14
    • 1970-01-01
    • 2018-06-11
    • 2014-12-29
    相关资源
    最近更新 更多