Playwright E2E测试中waitForEvent('page')超时问题求助
问题分析与修复方案
你的问题核心是错误判断了登录跳转的方式:
- 你用
context.waitForEvent('page')是等待浏览器打开新标签页/窗口,但实际登录后是在当前页面内导航跳转,这个事件根本不会触发,所以代码一直卡在等待新页面,最终超时。 - 截图显示已经跳转,说明登录操作是让当前页面URL发生变化,而非打开新页面。
修复步骤
直接修改登录提交后的逻辑,放弃等待新page事件,转而等待当前页面的导航完成:
修正后的代码
const {expect, test} = require('@playwright/test'); const { signUrl, testUser, homeUrl, } = require('../data/const'); test.describe('E2E Social', () => { test.beforeEach(async ({page}, testInfo) => { console.log(`Running ${testInfo.title}`); }); test.describe('sign in page', () => { test('can sign in', async ({ page }) => { await page.goto(signUrl); await page.locator('input[type="email"]').first().fill(testUser.login); await page .locator('input[type="password"]') .first() .fill(testUser.pwd); const submitButton = page.locator('input[type="submit"]'); await expect(submitButton).toBeVisible(); await expect(submitButton).toHaveText('Log in'); // 等待当前页面导航完成,而非新页面 await Promise.all([ page.waitForNavigation(), submitButton.click(), ]); // 直接断言当前页面的URL await expect(page.url()).toBe(homeUrl); }); }); });
额外优化建议
- 去掉不必要的
waitForTimeout(5000),Playwright的断言会自动等待元素/状态满足,硬编码等待时间既低效又不稳定。 - 如果登录后有加载动画或异步数据请求,可以用
page.waitForLoadState('networkidle')代替waitForNavigation,确保页面完全加载完成再执行断言。
内容的提问来源于stack exchange,提问作者byCoder
相关产品推荐
相关产品推荐

