元素码农
基础
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:21
↑
☰
# 常见错误代码解析 本文将详细介绍Playwright测试中常见的错误代码及其解决方案,帮助你快速定位和修复测试问题。 ## 浏览器错误 ### 1. 启动错误 ```typescript // 错误:无法启动浏览器 // Error: Failed to launch browser try { const browser = await chromium.launch(); } catch (error) { if (error.message.includes('Failed to launch browser')) { // 检查系统依赖 console.error('请确保系统安装了必要的依赖'); // 重新安装浏览器 await chromium.install(); } } // 解决方案 const browser = await chromium.launch({ // 添加必要的启动参数 args: [ '--no-sandbox', '--disable-setuid-sandbox', '--disable-dev-shm-usage' ] }); ``` ### 2. 连接错误 ```typescript // 错误:连接超时 // Error: Connection timeout try { await page.goto('https://example.com'); } catch (error) { if (error.message.includes('net::ERR_CONNECTION_TIMED_OUT')) { // 增加超时时间 await page.goto('https://example.com', { timeout: 60000, waitUntil: 'networkidle' }); } } ``` ## 元素错误 ### 1. 定位错误 ```typescript // 错误:元素未找到 // Error: Element not found try { await page.click('.non-existent'); } catch (error) { if (error.message.includes('Element not found')) { // 等待元素出现 await page.waitForSelector('.non-existent', { state: 'visible', timeout: 5000 }); } } // 解决方案:使用更可靠的选择器 await page.getByRole('button', { name: '提交' }).click(); await page.getByTestId('submit-button').click(); ``` ### 2. 操作错误 ```typescript // 错误:元素不可交互 // Error: Element is not clickable try { await page.click('button'); } catch (error) { if (error.message.includes('Element is not clickable')) { // 等待元素可交互 await page.waitForSelector('button', { state: 'visible', timeout: 5000 }); // 确保元素在视图中 await page.locator('button').scrollIntoViewIfNeeded(); } } ``` ## 网络错误 ### 1. 请求错误 ```typescript // 错误:请求失败 // Error: Request failed try { const response = await page.goto('https://api.example.com'); if (!response.ok()) { throw new Error(`HTTP error! status: ${response.status()}`); } } catch (error) { // 处理不同的HTTP错误 switch (error.status) { case 404: console.error('页面未找到'); break; case 500: console.error('服务器错误'); break; default: console.error('网络错误:', error); } } ``` ### 2. 超时错误 ```typescript // 错误:请求超时 // Error: Request timeout try { await page.waitForResponse('**/api/data', { timeout: 5000 }); } catch (error) { if (error.message.includes('Timeout')) { console.error('请求超时,可能的原因:'); console.error('1. 网络连接不稳定'); console.error('2. 服务器响应慢'); console.error('3. 超时时间设置过短'); } } ``` ## 测试错误 ### 1. 断言错误 ```typescript // 错误:断言失败 // Error: Assertion failed try { await expect(page.locator('.message')).toHaveText('成功'); } catch (error) { if (error.message.includes('expect')) { // 打印实际值 const actualText = await page.locator('.message').textContent(); console.error('期望值: 成功'); console.error('实际值:', actualText); // 截图保存 await page.screenshot({ path: 'assertion-error.png' }); } } ``` ### 2. 超时错误 ```typescript // 错误:测试超时 // Error: Test timeout test('长时间测试', async ({ page }) => { test.setTimeout(60000); // 设置更长的超时时间 try { await page.goto('https://example.com'); await page.waitForSelector('.slow-loading-element'); } catch (error) { if (error.message.includes('Test timeout')) { console.error('测试超时,建议:'); console.error('1. 增加超时时间'); console.error('2. 优化等待策略'); console.error('3. 检查性能问题'); } } }); ``` ## 最佳实践 ### 1. 错误处理 ```typescript // 创建错误处理器 class ErrorHandler { static async handle(error: Error, page: Page) { // 记录错误信息 console.error('错误类型:', error.name); console.error('错误消息:', error.message); console.error('堆栈跟踪:', error.stack); // 保存错误现场 await page.screenshot({ path: `error-${Date.now()}.png`, fullPage: true }); // 收集页面信息 const url = page.url(); const content = await page.content(); const console = await page.evaluate(() => { return console.logs; }); return { error, context: { url, content, console } }; } } ``` ### 2. 调试工具 ```typescript // 创建调试工具 class DebugTools { static async inspectElement(page: Page, selector: string) { const element = page.locator(selector); // 检查元素状态 const isVisible = await element.isVisible(); const isEnabled = await element.isEnabled(); const box = await element.boundingBox(); // 高亮元素 await element.highlight(); return { visible: isVisible, enabled: isEnabled, position: box, html: await element.evaluate(el => el.outerHTML) }; } } ``` ## 常见解决方案 ### 1. 稳定性问题 ```typescript // 处理不稳定的测试 test('不稳定的测试', async ({ page }) => { // 增加重试次数 test.retries(3); // 使用更可靠的等待策略 await Promise.all([ page.waitForResponse('**/api/data'), page.waitForSelector('.content', { state: 'visible' }), page.click('button') ]); }); ``` ### 2. 性能问题 ```typescript // 处理性能问题 test('性能测试', async ({ page }) => { // 监控页面性能 const performanceEntries = await page.evaluate(() => { return performance.getEntriesByType('navigation'); }); // 设置合理的超时时间 test.slow(); // 优化资源加载 await page.route('**/*.{png,jpg,jpeg}', route => route.abort()); }); ``` ## 下一步 1. 学习[元素定位失败分析](/article/playwright/troubleshooting/locator-failures) 2. 了解[浏览器启动问题排查](/article/playwright/troubleshooting/browser-launch) 3. 探索[测试用例组织结构](/article/playwright/best-practices/test-organization) ## 参考资料 - [Playwright错误处理](https://playwright.dev/docs/debug) - [Playwright调试指南](https://playwright.dev/docs/trace-viewer) - [测试稳定性建议](https://playwright.dev/docs/test-retries)