2013-12-04 2 views
16

У меня есть функция почтовой программы, которую я создал и пытаюсь укрепить покрытие. Попытка проверить его части оказались сложнее, особенно это mailer.smtpTransport.sendMailСмыкая функцию электронной почты в nodejs

var nodemailer = require('nodemailer') 

var mailer = {} 

mailer.smtpTransport = nodemailer.createTransport('SMTP', { 
    'service': 'Gmail', 
    'auth': { 
     'XOAuth2': { 
      'user': '[email protected]', 
      'clientId': 'googleClientID', 
      'clientSecret': 'superSekrit', 
      'refreshToken': '1/refreshYoSelf' 
     } 
    } 
}) 
var mailOptions = { 
    from: 'Some Admin <[email protected]>', 
} 

mailer.verify = function(email, hash) { 
    var emailhtml = 'Welcome to TestCo. <a href="'+hash+'">Click this '+hash+'</a>' 
    var emailtxt = 'Welcome to TestCo. This is your hash: '+hash 
    mailOptions.to = email 
    mailOptions.subject = 'Welcome to TestCo!' 
    mailOptions.html = emailhtml 
    mailOptions.text = emailtxt 
    mailer.smtpTransport.sendMail(mailOptions, function(error, response){ 
     if(error) { 
      console.log(error) 

     } else { 
      console.log('Message sent: '+response.message) 
     } 
    }) 
} 

Я уверен в том, как идти о тестировании, в частности, обеспечение того, чтобы моя функция mailer.smtpTransport.sendMail проходит правильные параметры без отправки электронной почты. Я пытаюсь использовать https://github.com/whatser/mock-nodemailer/tree/master, но я, вероятно, ошибаюсь. Должен ли я издеваться над методом?

var _ = require('lodash') 
var should = require('should') 
var nodemailer = require('nodemailer') 
var mockMailer = require('./helpers/mock-nodemailer') 
var transport = nodemailer.createTransport('SMTP', '') 

var mailer = require('../../../server/lib/account/mailer') 

describe('Mailer', function() { 
    describe('.verify()', function() { 
     it('sends a verify email with a hashto an address when invoked', function(done) { 
      var email ={ 
       'to': '[email protected]', 
       'html': 'Welcome to Testco. <a href="bleh">Click this bleh</a>', 
       'text': 'Welcome to Testco. This is your hash: bleh', 
       'subject': 'Welcome to Testco!' 
      } 

      mockMailer.expectEmail(function(sentEmail) { 
      return _.isEqual(email, sentEmail) 
      }, done) 
      mailer.verify('[email protected]','bleh') 
      transport.sendMail(email, function() {}) 
    }) 
}) 

ответ

16

Вы можете использовать транспортный уровень 'Stub' для вашего теста вместо SMTP.

var stubMailer = require("nodemailer").createTransport("Stub"), 
    options = { 
     from: "[email protected]", 
     to: "[email protected]", 
     text: "My Message!" 
    }; 

    stubMailer.sendMail(options, function(err, response){ 
    var message = response.message; 
    }) 

Таким образом, в этом случае «сообщение» будет являться адресом электронной почты в текстовом формате. Что-то вроде этого:

MIME-Version: 1.0 
X-Mailer: Nodemailer (0.3.43; +http://www.nodemailer.com/) 
Date: Fri, 25 Feb 2014 11:11:48 GMT 
Message-Id: <[email protected]> 
From: [email protected] 
To: [email protected] 
Content-Type: text/plain; charset=utf-8 
Content-Transfer-Encoding: quoted-printable 

My Message! 

Для большего количества примеров, посмотрите на nodemailer тестов: https://github.com/andris9/Nodemailer/blob/master/test/nodemailer-test.js

+3

В чем смысл этого теста? Как бы то ни было, это просто проверяет библиотеку nodemailer, которая уже тестируется в наборе тестов nodemailer. Почему бы не настроить фиктивный SMTP-сервер и проверить тестовые возможности? – Michael

2

expectEmail просто перехватывает на транспортном уровне, и ожидает, что вы определить электронную почту (возвращает истину, если это адрес, который вы ожидаете), посмотрев на содержимое sentEmail.

В этом случае должно быть достаточно return sentEmail.to === '[email protected]'.

Имейте в виду, что этот модуль был разработан в среде, где тесты выполняются в произвольном порядке и одновременно. Вы должны рандомизировать ваши данные в значительной степени, чтобы предотвратить столкновения и ложные срабатывания. BTW мы используем что-то вроде: var to = Date.now().toString(36) + Faker.Internet.email();

0

Этот пример отлично работает для меня

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

// SOME CODE HERE 

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

======== myfile.spec.js (блок тестовый файл) ========

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