Files
wenzi/frontend/e2e/utils/wait-helper.ts

95 lines
2.1 KiB
TypeScript
Raw Normal View History

/**
*
*
*/
import { Page, Locator } from '@playwright/test';
/**
* API响应
*/
export async function waitForApiResponse(
page: Page,
urlPattern: string | RegExp,
timeout: number = 10000
): Promise<any> {
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<void> {
await page.waitForLoadState('networkidle', { timeout });
await page.waitForLoadState('domcontentloaded', { timeout });
}
/**
*
*/
export async function waitForStableElement(
locator: Locator,
timeout: number = 5000
): Promise<void> {
await locator.waitFor({ state: 'visible', timeout });
await locator.waitFor({ state: 'stable', timeout });
}
/**
*
*/
export function sleep(ms: number): Promise<void> {
return new Promise(resolve => setTimeout(resolve, ms));
}
/**
*
*/
export async function waitForCondition(
condition: () => Promise<boolean> | boolean,
timeout: number = 5000,
interval: number = 100
): Promise<void> {
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<void> {
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}"超时`);
}