Node.js单元测试失败邮件通知及测试报告邮件发送实现问题咨询
实现单元测试邮件通知的两种方案
方案1:测试用例失败时实时发送通知
可以通过Mocha的全局钩子捕获失败用例,配合nodemailer实现实时触发邮件推送,具体实现步骤如下:
- 首先安装发邮件依赖:
npm install nodemailer --save-dev
- 在测试目录下新建全局钩子文件
test/hooks.js,写入以下逻辑:
const nodemailer = require('nodemailer'); // 配置邮件传输器,可根据你使用的邮箱服务商调整参数 const transporter = nodemailer.createTransport({ service: '163', // 支持QQ、Gmail、企业邮箱等 auth: { user: '你的发件邮箱地址', pass: '你的邮箱授权码' } }); // 全局钩子,每个测试用例执行完成后触发 afterEach(function() { // 判断当前用例是否执行失败 if (this.currentTest.state === 'failed') { const mailOptions = { from: '单元测试通知 <xxx@163.com>', to: '收件人邮箱地址', subject: `测试用例失败:${this.currentTest.title}`, text: `所属测试套件:${this.currentTest.parent.title}\n失败原因:${this.currentTest.err.message}\n错误堆栈:${this.currentTest.err.stack}` }; transporter.sendMail(mailOptions, (err) => { err && console.log('通知邮件发送失败:', err); }); } });
- 运行测试时引入钩子文件即可生效:
mocha test/**/*.test.js -r test/hooks.js
方案2:测试结束后发送完整测试报告
如果需要把Mocha测试报告、nyc覆盖率报告整体通过邮件发送,可以写一个自定义脚本统一执行测试+发报告,步骤如下:
- 首先安装mochawesome生成美观的HTML测试报告(如果已经用其他报告生成工具可跳过):
npm install mochawesome --save-dev
- 调整package.json中的测试命令,指定报告生成路径:
{ "scripts": { "test": "mocha test/**/*.test.js --reporter mochawesome --reporter-options reportDir=./test-report,reportFilename=index.html && nyc report --reporter=html" } }
- 新建脚本文件
test-with-notify.js,写入执行测试+发邮件的逻辑:
const { exec } = require('child_process'); const nodemailer = require('nodemailer'); const fs = require('fs'); const path = require('path'); // 邮件配置同方案1 const transporter = nodemailer.createTransport({ service: '163', auth: { user: '你的发件邮箱地址', pass: '你的邮箱授权码' } }); // 执行测试命令 exec('npm run test', (error, stdout, stderr) => { const hasFailedCase = error !== null; // 打开下面注释可配置为仅测试失败时才发邮件 // if (!hasFailedCase) return process.exit(0); const testReportPath = path.join(__dirname, './test-report/index.html'); const coverageReportPath = path.join(__dirname, './coverage/index.html'); const mailOptions = { from: '单元测试通知 <xxx@163.com>', to: '收件人邮箱地址', subject: hasFailedCase ? '单元测试运行失败,附完整报告' : '单元测试运行完成,附完整报告', // 直接把测试报告作为邮件正文展示 html: fs.readFileSync(testReportPath, 'utf-8'), // 附件添加测试报告和覆盖率报告 attachments: [ { filename: '测试报告.html', path: testReportPath }, { filename: '覆盖率报告.html', path: coverageReportPath } ] }; transporter.sendMail(mailOptions, (err) => { if (err) { console.log('报告邮件发送失败:', err); return process.exit(1); } console.log('报告邮件发送成功'); process.exit(hasFailedCase ? 1 : 0); }); });
- 在package.json添加对应运行命令即可使用:
{ "scripts": { "test:notify": "node test-with-notify.js" } }
注意:邮箱授权码等敏感信息不要硬编码到代码中,建议通过环境变量读取,避免信息泄露。
内容的提问来源于stack exchange,提问作者sotn
相关产品推荐
相关产品推荐

