You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Cypress中用Nodemailer发报告?遇sendAnEmail不是函数错误

在Cypress中使用Nodemailer的正确方式及报错修复

报错原因分析

你遇到的sendAnEmail is not a function错误源于三个核心问题:

  1. 导入错误:Cypress配置文件中require("nodemailer")导入的是Nodemailer核心包,而非你自定义的发送邮件函数。
  2. 函数语法错误:自定义邮件文件中存在重复定义同名函数、语法结构缺失的问题,导致函数无法正常导出。
  3. 异步处理缺失:client.sendMail是异步操作,未用Promise包裹的话,Cypress Task无法等待操作完成,会直接返回未定义结果,同时无法正确捕获返回值。

分步修复方案

1. 修正自定义邮件发送函数文件

修复语法错误,将回调式发送逻辑转为Promise,并正确导出函数:

// nodemailer.js(自定义文件,确保路径与配置文件对应)
const nodemailer = require('nodemailer');
const sgTransport = require('nodemailer-sendgrid-transport');

const sendAnEmail = (message) => {
  return new Promise((resolve, reject) => {
    const options = {
      auth: {
        user: "glorioustester123@outlook.com",
        pass: "********."
      }
    };
    const client = nodemailer.createTransport(sgTransport(options));

    const email = {
      from: 'glorioustester123@outlook.com',
      to: 'some.email@gmail.com',
      subject: 'Hello',
      text: message,
      html: '<b>Hello world</b>'
    };

    client.sendMail(email, function(err, info) {
      err ? reject(err.message) : resolve('Message sent: ' + info.response);
    });
  });
};

module.exports = sendAnEmail;

2. 修正Cypress配置文件

导入自定义的sendAnEmail函数,替换原有的Nodemailer包导入:

// Cypress config file
const { defineConfig } = require("cypress");
// 路径需对应你的自定义nodemailer文件位置,示例为当前目录下的nodemailer.js
const sendAnEmail = require("./nodemailer");

module.exports = defineConfig({
  pageLoadTimeout: 180000,
  e2e: {
    setupNodeEvents(on, config) {
      on('task', {
        sendMail (message) {
          return sendAnEmail(message);
        }
      });
    },
  },
});

3. 测试文件钩子逻辑保持不变

你的after钩子代码无需修改,现在可正确捕获邮件发送结果:

/// <reference types = "cypress" />

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

// 以下测试用例保持原有逻辑即可...

额外注意事项

  • 确保依赖包已安装:执行npm install nodemailer nodemailer-sendgrid-transport --save-dev
  • 邮件授权信息(如密码)建议通过环境变量管理,避免硬编码泄露敏感数据。

内容的提问来源于stack exchange,提问作者Dave Han

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.10 01:31:02