【发布时间】:2017-03-29 05:12:23
【问题描述】:
刚开始使用 jest,文档似乎对 mock 不太清楚。
我有一个带有以下代码的模块。如果我想测试发送邮件功能,但不通过 mailgun 发送实际电子邮件,我需要在这里做什么?我认为在我的测试文件中我需要使用模拟行为,但无法弄清楚如何专门阻止邮件发出,同时还能够检查是否遵循了正确的路线,例如无效的电子邮件地址、抛出的错误等。我需要进一步分解此功能吗?
const Mailgun = require('machinepack-mailgun');
const Emailaddresses = require('machinepack-emailaddresses');
const config = require('../Config');
// Function to send an email
const sendEmail = function (toaddress, toname, sub, msg, cb) {
// Validate the email address is correct and if so send an email. Otherwise log the error and exit.
Emailaddresses.validate({
string: toaddress,
}).exec({
error(err) {
return cb(err, null);
},
invalid() {
return cb(new Error('Email address is not valid.'), null);
},
success() {
Mailgun.sendPlaintextEmail({
apiKey: config.sender.apiKey,
domain: config.sender.domain,
toEmail: toaddress,
toName: toname,
subject: sub,
message: msg,
fromEmail: config.sender.fromEmail,
fromName: config.sender.fromName,
}).exec({
error(err) {
return cb(err, null);
},
success() {
return cb(null, 'Email Sent.');
},
});
},
});
};
module.exports.sendEmail = sendEmail;
【问题讨论】:
标签: unit-testing email jestjs