Playwright中处理删除文章确认弹窗的测试问题求助
解决Playwright删除文章时未触发确认弹窗的问题
问题核心
你踩的坑是混淆了Playwright的popup和dialog事件:网站弹出的是浏览器原生确认弹窗(confirm dialog),不是新窗口/标签页,所以用page.waitForEvent('popup')完全不对,自然会超时。
正确处理方案
Playwright专门提供dialog事件处理浏览器原生的alert、confirm、prompt弹窗,必须在点击删除按钮之前注册监听,避免弹窗出现后才监听导致错过事件。
修改后的完整测试代码
const {test, expect} = require('@playwright/test'); const { createNewArticle, generateRandomUser, generateRandomArticle } = require('../../helpers'); test.only('should delete an article after clicking on [Delete Article]', async ({page}) => { const user = generateRandomUser(); const article = generateRandomArticle(); const r = await createNewArticle(user, article); const slug = r.data.article.slug; const {email, password} = user; await page.goto('https://conduit.mate.academy/user/login'); await page.getByPlaceholder('Email').fill(email); await page.getByPlaceholder('Password').fill(password); await page.getByRole('button', { name: 'Sign in' }).click(); await page.waitForURL('https://conduit.mate.academy/'); await page.goto(`https://conduit.mate.academy/article/${slug}`); // 关键:点击删除按钮前,提前监听dialog并自动确认 page.on('dialog', async dialog => { // 可选:仅处理确认类型的弹窗,避免误操作其他弹窗 if (dialog.type() === 'confirm') { await dialog.accept(); } }); // 点击删除按钮触发弹窗 await page.locator('.btn.btn-outline-danger.btn-sm').first().click(); await page.goto(`https://conduit.mate.academy/profile/${user.username}`); await expect(page.locator('.article-preview')).toHaveCount(1); await expect(page.locator('.article-preview')).toHaveText('No articles are here... yet.'); })
补充说明
popup事件仅针对新打开的浏览器窗口/标签页,和原生弹窗完全不是一个类型,所以之前的方法根本抓不到目标弹窗。- 必须提前注册
dialog监听,要是等点击删除按钮后再注册,弹窗已经弹出,监听会错过事件,依然会超时。
内容的提问来源于stack exchange,提问作者Stepash
相关产品推荐
相关产品推荐

