Jared
Jared

Reputation: 2133

How to stub a nodejs "required" constructor using sinon?

I'm writing unit tests for a method that uses the email-templates module like this:

var EmailTemplate = require('email-templates').EmailTemplate;

module.exports = {
    sendTemplateEmail: function (emailName, data, subject, to, from) {
        var template = new EmailTemplate(__dirname + "/../emails/" + emailName);

        data.from = FROM;
        data.host = config.host;

        return template.render(data)
            .then(function (result) {
                return mailer.sendEmail(subject, to, from, result.html, result.text);
            })
            .then(function () {
                log.info(util.format("Sent %s email to %s. data=%s", emailName, to, JSON.stringify(data)));
                return Promise.resolve();
            })
            .catch(function (err) {
                return Promise.reject(new InternalError(err, "Error sending %s email to %s. data=%s", emailName, to, JSON.stringify(data)));
            });
    }
};

The unit test looks like this:

var assert = require("assert"),
    sinon = require("sinon"),
    Promise = require("bluebird"),
    proxyquire = require("proxyquire");

describe('mailer#sendTemplateEmail', function () {
    var templates,
        template;

    beforeEach(function() {
        templates = {
            EmailTemplate: function(path) {}
        };
        template = {
            render: function(data) {}
        };

        sinon.stub(templates, "EmailTemplate").returns(template);
    });

    it("should reject immediately if template.render fails", function () {
        const TO = {email: "[email protected]", first: "User"};
        const FROM = {email: "[email protected]", first: "User"};
        const EMAIL_NAME = "results";
        const SUBJECT = "Results are in!";
        const DATA = {
            week: 10,
            season: "2015"
        };

        var err = new Error("error");
        var mailer = proxyquire("../src/mailer", {
            "email-templates": templates
        });

        sinon.stub(template, "render").returns(Promise.reject(err));

        return mailer.sendTemplateEmail(EMAIL_NAME, DATA, SUBJECT, TO, FROM)
                .then(function () {
                    assert.fail("Expected a rejected promise.");
                })
                .catch(function (err) {
                    assert(err.message === "error");
                    assert(mailer.sendEmail.notCalled);
                });
    });
};

The problem I'm encountering is on the first line of the sendTemplateEmail function which instantiates a new EmailTemplate object. The EmailTemplate constructor being called points to the non-stub EmailTemplate function defined in the beforeEach, rather than the sinon stub created on the last line of the beforeEach. If I evaluate the require('email-templates').EmailTemplate statement, however, it correctly points to the sinon stub. I'd prefer not to have to change my code to call the require statement inline like:

var template = new require('email-templates').EmailTemplate(__dirname + "/../emails/" + emailName);

Is there any way to accomplish the stub the way I'm intending?

Upvotes: 1

Views: 1400

Answers (1)

Tim
Tim

Reputation: 549

You can inject your dependency when you construct your mailer - exp:

function mailer(options) {
  options = options || {};
  this.email_template = options.email_template;
}

Then in the sendTemplateEmail function - use the email_template member.

Also - not sure about your mailer code - but if you need your mailer to act as a singleton in your code (and it isn't already) - you can add this to your mailer:

module.exports = {
    getInstance: function(emailTemplate) {
        if(this.instance === null){
            this.instance = new mailer(emailTemplate);
        }
        return this.instance;
    }
}

Then when you require your mailer you can use the syntax:

var template = new require('email-templates').EmailTemplate(__dirname + "/../emails/" + emailName);
var mail = mailer.getInstance(template);

This way your application (unit test framework or your actual/real-world application) will determine the type of mailer that will be used for the lifetime of the process.

Upvotes: 1

Related Questions