【问题标题】:How to send an email with test report in Cypress如何在 Cypress 中发送带有测试报告的电子邮件
【发布时间】:2021-02-08 17:35:50
【问题描述】:

我正在努力实现以下目标:

  1. 创建仅包含测试名称和状态(失败/通过)的简单测试报告
  2. 通过电子邮件将此报告作为基本 HTML 发送。

为此,我需要:

  1. 一个基本的记者而不是默认的
  2. 库,可以发送电子邮件。我已经尝试过nodemailer。但是,当我将它与赛普拉斯解决方案连接时,它不会发送任何电子邮件。我尝试了不同的邮箱帐户(nodemailer.createTestAccount(),一个来自我的公司,一个来自 SendGrid),但都不起作用(我没有收到任何电子邮件)

关于第 2 点,这是我使用的代码示例。这是 index.js 文件中的代码 - 我需要在所有测试后发送它:

after(() => {

var nodemailer = require('nodemailer');
var sgTransport = require('nodemailer-sendgrid-transport');

var options = {
  auth: {
    api_user: 'sendgrid_USER',
    api_key: 'sendgrid_APIKEY'
  }
}

var client = nodemailer.createTransport(sgTransport(options));

var email = {
    from: 'FROM_MAIL.PL',
    to: 'TO_MAIL.PL',
  subject: 'Hello',
  text: 'Hello world',
  html: '<b>Hello world</b>'
};

client.sendMail(email, function(err, info){
    if (err ){
      console.log(error);
    }
    else {
      console.log('Message sent: ' + info.response);
    }
});

});

【问题讨论】:

  • “不工作”到底是什么意思?能否请edit该问题并添加任何错误消息或退回原因?
  • @Robert 我会更新,但是,问题是 t 没有发送任何电子邮件。我目前不知道为什么

标签: email cypress nodemailer test-reporting


【解决方案1】:

Nodemailer 是 Node.js 的一个模块,因此您需要在 Cypress 任务中运行它。

将此添加到您的 /cypress/plugins/index.js 文件中

const sendAnEmail = (message) => {

  const nodemailer = require('nodemailer');
  const sgTransport = require('nodemailer-sendgrid-transport');
  const options = {
    auth: {
      api_user: 'sendgrid_USER',
      api_key: 'sendgrid_APIKEY'
    }
  }
  const client = nodemailer.createTransport(sgTransport(options));

  const email = {
    from: 'FROM_MAIL.PL',
    to: 'TO_MAIL.PL',
    subject: 'Hello',
    text: message,
    html: '<b>Hello world</b>'
  };
  client.sendMail(email, function(err, info) {
    return err? err.message : 'Message sent: ' + info.response;
  });
}

module.exports = (on, config) => {
  on('task', {
    sendMail (message) {
      return sendAnEmail(message);
    }
  })
}

然后在测试中(或在 /cypress/support/index.js 中进行所有测试)

after(() => {
  cy.task('sendMail', 'This will be output to email address')
    .then(result => console.log(result));
})

这是对示例here 的基本重构,您可以根据自己的要求进行调整。

【讨论】:

  • 我想做的是从 Index.js 发送这封电子邮件,因为这需要在所有测试之后完成(after 部分)。我也可以在那里运行这个任务吗?所以你的两个例子都在 index.js
  • 是的,您可以在 /cypress/support/index.js 中的 after() 挂钩中运行任务(不要与 /cypress/plugins/ 混淆index.js 定义任务的地方)。
  • 谢谢!现在一切都清楚了。发送电子邮件效果很好。我只需要了解如何准备一份简单的测试报告
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-02-18
  • 1970-01-01
  • 1970-01-01
  • 2017-06-17
  • 2016-02-28
相关资源
最近更新 更多