gpt4 book ai didi

node.js - 在nodejs中模拟电子邮件功能

转载 作者:IT老高 更新时间:2023-10-28 23:00:00 25 4
gpt4 key购买 nike

我已经构建了一个邮件功能,并试图加强覆盖范围。尝试测试它的某些部分已被证明很棘手,特别是这个 mailer.smtpTransport.sendMail

var nodemailer = require('nodemailer')

var mailer = {}

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

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 ,但我可能做错了。我应该 mock 这个方法吗?

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': 'dave@testco.com',
'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('dave@testco.com','bleh')
transport.sendMail(email, function() {})
})
})

最佳答案

您可以在测试中使用“ stub ”传输层而不是 SMTP。

var stubMailer = require("nodemailer").createTransport("Stub"),
options = {
from: "from@email.com",
to: "to@email.com",
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: <123412341234.e23232@Nodemailer>
From: from@email.com
To: to@email.com
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

关于node.js - 在nodejs中模拟电子邮件功能,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20387034/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com