/** * 等待辅助工具 * 提供各种等待条件的辅助函数 */ import { Page, Locator } from '@playwright/test'; /** * 等待API响应 */ export async function waitForApiResponse( page: Page, urlPattern: string | RegExp, timeout: number = 10000 ): Promise { return await page.waitForResponse( response => { const matches = typeof urlPattern === 'string' ? response.url().includes(urlPattern) : urlPattern.test(response.url()); return matches && response.status() === 200; }, { timeout } ); } /** * 等待页面加载完成 */ export async function waitForPageLoad(page: Page, timeout: number = 10000): Promise { await page.waitForLoadState('networkidle', { timeout }); await page.waitForLoadState('domcontentloaded', { timeout }); } /** * 等待元素可见并稳定 */ export async function waitForStableElement( locator: Locator, timeout: number = 5000 ): Promise { await locator.waitFor({ state: 'visible', timeout }); await locator.waitFor({ state: 'stable', timeout }); } /** * 等待指定时间 */ export function sleep(ms: number): Promise { return new Promise(resolve => setTimeout(resolve, ms)); } /** * 等待条件满足 */ export async function waitForCondition( condition: () => Promise | boolean, timeout: number = 5000, interval: number = 100 ): Promise { const startTime = Date.now(); while (Date.now() - startTime < timeout) { const result = await condition(); if (result) { return; } await sleep(interval); } throw new Error('等待条件超时'); } /** * 等待元素包含特定文本 */ export async function waitForText( locator: Locator, text: string, timeout: number = 5000 ): Promise { await locator.waitFor({ timeout }); const startTime = Date.now(); while (Date.now() - startTime < timeout) { const elementText = await locator.textContent(); if (elementText?.includes(text)) { return; } await sleep(100); } throw new Error(`等待文本"${text}"超时`); }