如何在Cucumber/Playwright的TypeScript代码中调整新页面尺寸
问题描述
现有如下方法:
public async openWindow(): Promise<void> { console.info("driver-manager: get new page ..."); const [newPage] = await Promise.all([(await this.context).waitForEvent("page")]); console.info("driver-manager: got new page ..."); await newPage.waitForLoadState("networkidle"); this.page = newPage; }
通过const [newPage] = await ...获取的新窗口中,有两个Cucumber/Playwright测试必需的按钮不可见,怀疑因此导致测试超时失败。已定义视口配置对象但不知如何应用:
const playwrightBrowserResolution = { viewport: { width: 1920, height: 1080 } };
解决方案
方法1:获取新页面后直接设置视口
修改openWindow方法,在获取到newPage后立即调用setViewportSize设置窗口尺寸:
public async openWindow(): Promise<void> { console.info("driver-manager: get new page ..."); const [newPage] = await Promise.all([(await this.context).waitForEvent("page")]); console.info("driver-manager: got new page ..."); // 应用预设的视口尺寸 await newPage.setViewportSize(playwrightBrowserResolution.viewport); await newPage.waitForLoadState("networkidle"); this.page = newPage; }
方法2:创建浏览器上下文时全局配置视口
如果this.context是你自行创建的(比如通过browser.newContext()),可以在创建上下文时直接传入视口配置,这样该上下文下打开的所有页面都会默认使用这个尺寸:
// 创建上下文时传入视口配置,后续页面自动继承 this.context = await browser.newContext(playwrightBrowserResolution);
额外优化:确保元素可见
如果按钮不可见是因为被页面内容遮挡,可添加滚动操作确保元素进入视口:
// 替换为你的按钮选择器 await newPage.locator("button.target-btn").scrollIntoViewIfNeeded();
内容的提问来源于stack exchange,提问作者Mark S
相关产品推荐
相关产品推荐

