【问题标题】:Callback for sendmail transport never called in the after hook in the mocha在 mocha 的 after 挂钩中从未调用过 sendmail 传输的回调
【发布时间】:2017-03-20 05:21:24
【问题描述】:

我想在执行完所有测试后发送包含测试结果的电子邮件。

当我在 after 挂钩中调用 sendMail (nodemailer) 时 - 它不起作用。

我的代码:

after(function(done) {
     sendReport();
     done();
});


function sendReport() {
   let mailOptions = {
        from: "xxx@gmail.com",
        to: "xxx@gmail.com",
        subject: "subject",
        text: "body Text",
        html: "<h2><b>TEXT.</b></h2>",
        attachments: [{
            path: "../reports/report.html"
        }]
    };

    let transporter = nodemailer.createTransport({
        service: "Gmail",
        auth: {
            user: "xxx@gmail.com",
            pass: "xxxx"
        }
    });

    transporter.sendMail(mailOptions, function (error, info) {
         if (error) {
            console.log(error);
        }
    });
}

【问题讨论】:

  • 您必须在邮件发送之后调用done回调(注意异步)

标签: javascript unit-testing asynchronous mocha.js nodemailer


【解决方案1】:
let mailTransport = nodemailer.createTransport(mailConfig);
mailTransport.sendMail(mailOptions, function(err, info){
    if (err) {
        console.log('ERRO');
        console.log(err.message);
        return process.exit(1);
    }
    console.log("messageId",info.messageId);
    console.log("envelope", info.envelope);
    console.log("accepted", info.accepted);
    console.log("rejected", info.rejected);
    console.log("pending", info.pending);
    console.log("response", response );
    console.log('SCSS', numero, mailOptions.to, termo);
});

【讨论】:

    【解决方案2】:

    发送邮件后执行done回调:

    after(function(done) {
         sendReport(done);
    });
    
    
    function sendReport(done) {
       let mailOptions = {
            from: "xxx@gmail.com",
            to: "xxx@gmail.com",
            subject: "subject",
            text: "body Text",
            html: "<h2><b>TEXT.</b></h2>",
            attachments: [{
                path: "../reports/report.html"
            }]
        };
    
        let transporter = nodemailer.createTransport({
            service: "Gmail",
            auth: {
                user: "xxx@gmail.com",
                pass: "xxxx"
            }
        });
    
        transporter.sendMail(mailOptions, function (error, info) {
             if (error) {
                console.log(error);
            }
            done();
        });
    }
    

    【讨论】:

    • 太棒了!非常感谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-11-01
    • 2014-12-24
    • 2020-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-03
    相关资源
    最近更新 更多