Playwright实现Page Object Model时URL断言失败问题
问题分析与修复方案
你的断言失败核心原因是代码存在两处语法错误,导致按钮点击操作未实际执行,页面自然无法跳转:
1. 元素定位语法错误
client_login_button的getByRole参数多了一个左括号,正确写法应为:
this.client_login_button = page.getByRole('link', { name: 'CLIENT LOGIN' })
原代码里的(('link'属于无效语法,会导致元素定位失败,后续点击操作无法执行。
2. 未调用click方法
click是Playwright元素的异步方法,必须加括号调用才能触发点击动作,原代码里的await this.login_button.click仅引用了方法,未实际执行。正确写法是:
await this.login_button.click() await this.client_login_button.click()
修复后的HomePage类代码
exports.HomePage = class HomePage { constructor(page) { this.page = page this.login_button = page.getByRole('button', { name: 'Login' }) this.client_login_button = page.getByRole('link', { name: 'CLIENT LOGIN' }) } async gotoHomePage(){ await this.page.goto('https://plentifulapp.com/'); await this.login_button.click() await this.client_login_button.click() } }
额外优化建议
如果页面跳转较慢,断言可能因超时失败,可以给断言增加超时时间,或在点击时显式等待导航完成:
// 给断言增加超时时间(单位:毫秒) await expect(page).toHaveURL('https://app.plentifulapp.com/a/pantries', { timeout: 10000 }) // 或者在触发跳转的点击操作中等待导航完成 await this.client_login_button.click({ waitForNavigation: 'networkidle' })
内容的提问来源于stack exchange,提问作者Subtain Shah
相关产品推荐
相关产品推荐

