如何存根nodejs" required"使用sinon的构造函数?

时间:2015-12-24 19:39:05

标签: node.js unit-testing mocha sinon proxyquire

我正在为使用email-templates模块的方法编写单元测试:

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

单元测试如下:

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: "user1@example.com", first: "User"};
        const FROM = {email: "user2@example.com", 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);
                });
    });
};

我遇到的问题是sendTemplateEmail函数的第一行,它实例化了一个新的EmailTemplate对象。被调用的EmailTemplate构造函数指向EmailTemplate中定义的非存根beforeEach函数,而不是beforeEach最后一行创建的sinon存根。但是,如果我评估require('email-templates').EmailTemplate语句,它正确地指向了sinon存根。我不想更改我的代码来内联调用require语句,如:

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

有没有办法以我想要的方式完成存根?

1 个答案:

答案 0 :(得分:1)

您可以在构建邮件时注入依赖项--exp:

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

然后在sendTemplateEmail函数中 - 使用email_template成员。

此外 - 不确定您的邮件代码 - 但如果您需要将邮件程序作为代码中的单身人士(而且还没有) - 您可以将其添加到邮件程序中:

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

然后,当您需要邮件时,您可以使用以下语法:

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

这样,您的应用程序(单元测试框架或您的实际/实际应用程序)将确定将在该过程的生命周期中使用的邮件程序的类型。