首页 > 解决方案 > 如何在 Cypress 中发送带有测试报告的电子邮件

问题描述

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

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

});

标签: emailcypressnodemailertest-reporting

解决方案


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

这是此处示例的基本重构,您可以根据需要进行调整。


推荐阅读