2

Here, I want to assert that callback function is called or not. So how can I do it using sinon js. Please suggest.

var send = function (templateId, callback) {

    const request = mailjet
        .post("send")
        .request(params)
    request
        .then((result) => {
            if (typeof callback === 'function') {
                callback(null, result.body);
            }

        })
        .catch((err) => {
            if (typeof callback === 'function') {
                callback(err, null);
            }
        })
    } else {
        callback(err, null);
    }
};

I have tried as following:

var mailjetClient = require('../../node_modules/node-mailjet/mailjet-client');

sinon.stub(mailjet, 'post').withArgs('send').returns(mailjetClient);
sinon.stub(mailjetClient, 'request').returns(Promise);

I am getting following error:

TypeError: Attempted to wrap undefined property request as function
Jigar Pancholi
  • 1,209
  • 1
  • 8
  • 25

1 Answers1

3

Try this it will work, you have to specify what post method return, then return and request return.

   var cb = sinon.spy();

   var obj = {successId: 12121};  // Any success response

   var then = sinon.stub().callsArgWith(0, obj).returns(
        {
            catch: sinon.stub()
        }
    );

    var request = sinon.stub().returns(
        {
            then: then
        }
    );

    sinon.stub(mailjet, "post", () => {
        return {
            request: request
        };
    });

    mailSender.send(templateName, cb);
    sinon.assert.calledOnce(cb);
    mailjet.post.restore();
Apoorva Shah
  • 632
  • 1
  • 6
  • 15