import { expect, type Page } from '@playwright/test';
/**
* 页面走查公共辅助
* - 收集 console/pageerror,断言走查时无前端错误(对照 e2e-testing 场景 #1 页面加载)
*/
/** 收集页面 console 错误与未捕获异常 */
export function collectErrors(page: Page) {
const errors: String[] = [];
page.on('console', (m) => {
if (m.type() === 'error') errors.push(`[console.error] ${m.text()}`);
});
page.on('pageerror', (e) => errors.push(`[pageerror] ${e.message}`));
return errors;
}
/** 页面加载后立即断言无 JS/console 错误 */
export async function expectNoErrors(errors: String[]) {
// 过滤资源 404 之类非脚本错误(保留真实 JS 错误)
const real = errors.filter(
(e) => !/Failed to load resource|net::ERR_|favicon/i.test(String(e)),
);
expect(real, `前端错误:\n${real.join('\n')}`).toEqual([]);
}
/** 断言页面 HTTP 状态非 4xx/5xx(拦截 response) */
export function watchHttp(page: Page) {
const bad: String[] = [];
page.on('response', (r) => {
if (r.status() >= 400) bad.push(`${r.status()} ${r.url()}`);
});
return bad;
}
/** 安全等待网络空闲(避免 SPA/懒加载) */
export async function settle(page: Page) {
await page.waitForLoadState('networkidle').catch(() => {});
}
|