简体   繁体   English

Javascript 测试 - 使用特定参数调用 function

[英]Javascript testing - function called with specfic argument

I am trying to write a unit test for a function but cannot figure out how to check if it makes a call to a nested function with a specific argument.我正在尝试为 function 编写单元测试,但无法弄清楚如何检查它是否使用特定参数调用嵌套的 function。 I am assuming I will need to use sinon alongside chai and mocha for this, but I could really use some help.我假设我需要将 sinon 与 chai 和 mocha 一起使用,但我真的可以使用一些帮助。

The function I would like to test looks like:我想测试的 function 看起来像:

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

I would like to test if next is called with or without the err variable.我想测试是否在有或没有 err 变量的情况下调用 next。 From what I read so far I should use a spy for this (I think) but how would I use that spy?从我目前阅读的内容来看,我应该为此使用间谍(我认为),但我将如何使用该间谍? Looking at this example from the Sinon docs it is unclear to me where PubSub comes from:从 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);
}

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

If you have a function like this如果您有这样的 function

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

The test could look like this测试可能看起来像这样

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);
});

so you don't necessarily need sinon for that所以你不一定需要sinon

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM