Playwright+TypeScript中try-catch无法按页面标题校验执行问题
自动化测试try-catch失效问题解决
场景与问题
测试逻辑:页面标题为「Example title」则直接通过;否则点击指定链接后再次校验标题。使用try-catch实现时,始终触发超时错误,代码无法进入catch块。
代码片段
try { await expect.soft(page).toHaveTitle("Example title",{ timeout: 30000 }) } catch (error){ await page.getByRole('link', { name: 'here' }).click(); await expect.soft(page).toHaveTitle("Example title",{ timeout: 30000 }) }
实际报错
Test timeout of 30000ms exceeded.
Error: expect(locator).toHaveTitle(expected) Locator: locator(':root') Expected string: "Example title" Received string: "Some Count Exceeded" Call log: - expect.soft.toHaveTitle with timeout 30000ms - waiting for locator(':root') - locator resolved to <html>…</html> - unexpected value "dfretgrt" ... > 19 | 20 | try { > 21 | await expect.soft(page).toHaveTitle("Example title",{ timeout: 30000 }) | ^ 22 | 23 | } 24 | catch (error){
问题原因
expect.soft是软断言,它不会抛出可被try-catch捕获的常规异常,只会将失败标记为测试中的软失败,不会中断代码执行。因此try块会一直等待断言通过,直到超时,最终触发测试超时错误,而非进入catch块。
解决方案
方案一:改用普通断言
普通断言expect失败时会抛出异常,能被try-catch正常捕获:
try { await expect(page).toHaveTitle("Example title", { timeout: 30000 }); } catch (error) { await page.getByRole('link', { name: 'here' }).click(); await expect(page).toHaveTitle("Example title", { timeout: 30000 }); }
方案二:主动检查标题(更推荐)
直接获取页面标题做判断,逻辑更清晰,无需依赖断言异常:
// 获取当前页面标题 const currentTitle = await page.title(); if (currentTitle !== "Example title") { await page.getByRole('link', { name: 'here' }).click(); // 等待页面跳转后校验标题 await expect(page).toHaveTitle("Example title", { timeout: 30000 }); }
内容的提问来源于stack exchange,提问作者Preetham
相关产品推荐
相关产品推荐

