如何测试使用nodemailer发送电子邮件的Sequelize'afterCreate'钩子?

时间:2015-04-30 21:56:09

标签: node.js unit-testing sequelize.js nodemailer

我有一个User续集模型,它使用models目录中的index.js文件加载,例如。

"use strict";

var fs        = require("fs");
var path      = require("path");
var Sequelize = require("sequelize");
var basename  = path.basename(module.filename);
var env       = process.env.NODE_ENV || "development";
var config    = require(__dirname + '/../../config/database.json')[env];
var sequelize = new Sequelize(config.database, config.username, config.password, config);
var db        = {};

fs
  .readdirSync(__dirname)
  .filter(function(file) {
   return (file.indexOf(".") !== 0) && (file !== basename);
 })
  .forEach(function(file) {
     var model = sequelize["import"](path.join(__dirname, file));
     db[model.name] = model;
 });

Object.keys(db).forEach(function(modelName) {
   if ("associate" in db[modelName]) {
   db[modelName].associate(db);
  }
});

 db.sequelize = sequelize;
 db.Sequelize = Sequelize;

 module.exports = db;

在我的模型中afterSave挂钩:

afterCreate : function(user, options, fn){
  mailer.sendEmailConfirmation(user.email, user.confirmation_code,   function(err){
      if(err){
        console.log(err);
      }
    });

    fn(null, user);
  } 

mailer是模型中需要的依赖项。我如何进行单元测试呢?我基本上想要将用户保存在mocha测试中并确保调用sendEmailConfirmation

1 个答案:

答案 0 :(得分:0)

使用模拟 - 使用默认情况下模拟所有内容的测试库(http://facebook.github.io/jest/)或者使用专用的模拟/存根库(例如sinon来模拟您关心的函数):

var stub = sinon.stub(mailer, 'sendEmailConfirmation', function (email ,code, fn) {
  fn(); // Your stub should invoke the callback, otherwise the hook will hang
});

user.save().then(function () {
  assert(stub.called())
});