3

I have a function I would like to test:

var mailServerOptions = {....};

var transporter = nodemailer.createTransport(mailServerOptions);

exports.sendTemplateEmail = (to, template, data) => {
    var mailOptions = {....}

    return new Promise((resolve, reject) => {
        transporter.sendMail(mailOptions, (err, result) => {
            if (err) {
                return reject(err)
            }

            return resolve(result);
        });
    });
}

How can I stub the transporter.sendMail in this situation? I found this post but it doesn't really fit what I'm trying to do.

I can move the send part to it's own function and stub that if I really have to, but it would be nice if I didn't have to go that route.

Mankind1023
  • 7,198
  • 16
  • 56
  • 86

1 Answers1

1

This example works fine for me

======== myfile.js ========

// SOME CODE HERE

transporter.sendMail(mailOptions, (err, info) => {
  // PROCESS RESULT HERE
});

======== myfile.spec.js (unit test file) ========

const sinon = require('sinon');
const nodemailer = require('nodemailer');
const sandbox = sinon.sandbox.create();

descript('XXX', () => {
  it('XXX', done => {
    const transport = {
      sendMail: (data, callback) => {
        const err = new Error('some error');
        callback(err, null);
      }
    };
    sandbox.stub(nodemailer, 'createTransport').returns(transport);

    // CALL FUNCTION TO TEST

    // EXPECT RESULT
  });
});
Alongkorn
  • 3,968
  • 1
  • 24
  • 41