元素码农
基础
UML建模
数据结构
算法
设计模式
网络
TCP/IP协议
HTTPS安全机制
WebSocket实时通信
数据库
sqlite
postgresql
clickhouse
后端
rust
go
java
php
mysql
redis
mongodb
etcd
nats
zincsearch
前端
浏览器
javascript
typescript
vue3
react
游戏
unity
unreal
C++
C#
Lua
App
android
ios
flutter
react-native
安全
Web安全
测试
软件测试
自动化测试 - Playwright
人工智能
Python
langChain
langGraph
运维
linux
docker
工具
git
svn
🌞
🌙
目录
▶
入门指南
Playwright安装与配置
环境要求与验证
第一个自动化测试脚本
▶
核心概念
Browser对象详解
Page对象操作指南
Frame与上下文管理
网络请求拦截与Mock
▶
元素定位与操作
CSS选择器实战
XPath高级定位技巧
文本定位与正则匹配
动态元素等待策略
▶
高级操作指南
文件上传下载处理
多标签页与弹窗管理
浏览器上下文隔离
设备模拟与地理定位
▶
测试框架集成
Jest集成配置
Mocha测试报告生成
持续集成CI/CD配置
▶
最佳实践
测试用例组织结构
性能优化策略
跨浏览器测试方案
▶
疑难解答
常见错误代码解析
元素定位失败分析
浏览器启动问题排查
▶
录制功能指南
录制功能基础入门
录制脚本生成与编辑
高级录制配置与技巧
录制脚本调试与优化
发布时间:
2025-03-27 19:17
↑
☰
# Mocha测试报告生成 本文将详细介绍如何在Playwright与Mocha集成环境中生成测试报告,帮助你更好地管理和展示测试结果。 ## 基础配置 ### 1. 安装依赖 ```bash # 安装Mocha和相关依赖 npm install -D mocha @playwright/test mochawesome mochawesome-merge mochawesome-report-generator # 安装TypeScript支持 npm install -D ts-node typescript @types/mocha ``` ### 2. 配置Mocha ```javascript // .mocharc.js module.exports = { require: ['ts-node/register'], timeout: 30000, reporter: 'mochawesome', 'reporter-option': [ 'reportDir=test-results', 'reportFilename=[status]_[datetime]', 'html=true', 'json=true' ] }; ``` ### 3. 配置脚本 ```json // package.json { "scripts": { "test": "mocha 'tests/**/*.spec.ts' --reporter mochawesome", "report:merge": "mochawesome-merge test-results/*.json > test-results/report.json", "report:generate": "marge test-results/report.json -f report -o test-results" } } ``` ## 报告生成 ### 1. 基本报告 ```typescript // test/login.spec.ts describe('登录功能', () => { let browser, context, page; before(async () => { browser = await chromium.launch(); context = await browser.newContext(); page = await context.newPage(); }); after(async () => { await browser.close(); }); it('成功登录', async () => { await page.goto('https://example.com/login'); await page.fill('input[name="username"]', 'admin'); await page.fill('input[name="password"]', '123456'); await page.click('button[type="submit"]'); await expect(page).toHaveURL('https://example.com/dashboard'); }); }); ``` ### 2. 高级报告 ```typescript // test/api.spec.ts describe('API测试', () => { it('请求测试', async () => { // 添加自定义数据到报告 addContext(this, { title: '请求信息', value: { url: 'https://api.example.com/data', method: 'POST', headers: { 'Content-Type': 'application/json' } } }); const response = await page.request.post('https://api.example.com/data', { data: { test: true } }); // 添加响应数据到报告 addContext(this, { title: '响应数据', value: await response.json() }); expect(response.ok()).toBeTruthy(); }); }); ``` ## 报告定制 ### 1. 报告样式 ```javascript // .mocharc.js module.exports = { reporter: 'mochawesome', 'reporter-option': [ 'reportDir=test-results', 'reportTitle=自动化测试报告', 'reportPageTitle=测试结果', 'showPassed=true', 'showFailed=true', 'showPending=true', 'showSkipped=false', 'enableCode=true', 'enableChart=true' ] }; ``` ### 2. 自定义报告 ```typescript // reporters/custom.js class CustomReporter { constructor(runner) { runner.on('start', () => { console.log('开始测试...'); }); runner.on('pass', (test) => { console.log(`通过: ${test.fullTitle()}`); }); runner.on('fail', (test, err) => { console.log(`失败: ${test.fullTitle()} - ${err.message}`); }); runner.on('end', () => { console.log('测试完成'); }); } } module.exports = CustomReporter; ``` ## 最佳实践 ### 1. 报告组织 ```typescript // test/setup.ts import { addContext } from 'mochawesome/addContext'; export class TestReporter { static async addScreenshot(test, page) { const screenshot = await page.screenshot(); addContext(test, { title: '失败截图', value: screenshot.toString('base64') }); } static addError(test, error) { addContext(test, { title: '错误信息', value: error.stack }); } } ``` ### 2. 并行测试报告 ```javascript // .mocharc.js module.exports = { parallel: true, jobs: 4, reporter: 'mochawesome', 'reporter-option': [ 'reportDir=test-results/parallel', 'reportFilename=[status]_[datetime]_[worker]' ] }; ``` ## 调试技巧 ### 1. 报告调试 ```typescript // test/debug.spec.ts describe('调试测试', () => { beforeEach(function() { // 添加测试环境信息 addContext(this, { title: '测试环境', value: { browser: process.env.BROWSER, viewport: page.viewportSize(), url: page.url() } }); }); afterEach(async function() { if (this.currentTest.state === 'failed') { await TestReporter.addScreenshot(this, page); } }); }); ``` ### 2. 错误处理 ```typescript // test/error.spec.ts describe('错误处理', () => { it('捕获错误', async function() { try { await page.click('.non-existent'); } catch (error) { TestReporter.addError(this, error); throw error; } }); }); ``` ## 常见问题 ### 1. 报告合并 ```bash # 合并多个报告文件 npm run report:merge # 生成HTML报告 npm run report:generate ``` ### 2. 性能优化 ```javascript // .mocharc.js module.exports = { reporter: 'mochawesome', 'reporter-option': [ 'enableCode=false', // 禁用代码展示 'enableChart=false', // 禁用图表 'saveJson=false', // 不保存JSON文件 'overwrite=true' // 覆盖已有报告 ] }; ``` ## 下一步 1. 了解[持续集成CI/CD配置](/article/playwright/integration/ci-cd) 2. 探索[测试用例组织结构](/article/playwright/best-practices/test-organization) 3. 学习[性能优化策略](/article/playwright/best-practices/performance) ## 参考资料 - [Mocha官方文档](https://mochajs.org/) - [Mochawesome报告生成器](https://github.com/adamgruber/mochawesome) - [Playwright测试API](https://playwright.dev/docs/test-api-testing)