简体   繁体   中英

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. I am assuming I will need to use sinon alongside chai and mocha for this, but I could really use some help.

The function I would like to test looks like:

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. 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:

"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/

If you have a function like this

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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