Playwirght QA Testing Automation Web scraping waitForLoadState waitForResponse waitForRequest api api testing regression

Playwright : 'wait' For System Stability

張庭瑋 Gary Chang 2024/04/19 10:00:00

Wait For System Stability

Playwright provides several wait mechanisms that are more focused on overall page state, and network activities. We can use it for waiting for the application to reach a stable state after performing actions that might lead to a change in the page content or state.



The networkidle state is particularly useful for waiting until there are no more than 2 network connections for at least 500ms, indicating that most of the resources have been loaded.

await page.goto('');
await page.waitForLoadState('networkidle');



const { chromium } = require('playwright');

(async () => {
    const browser = await chromium.launch({ headless: false });
    const page = await browser.newPage();
    await page.goto('');

    await page.waitForLoadState('networkidle');

    console.log('Loading complete');
    await page.screenshot({ path: 'gmail.png' });

// adding actions after loaing success...

    await browser.close();


waitForResponse and waitForRequest

These method are useful for testing applications with significant backend interactions.


// Wait for a specific request
await page.waitForRequest(request => request.url().includes('/api/data') && request.method() === 'GET');

// Wait for a specific response
await page.waitForResponse(response => response.url().includes('/api/data') && response.status() === 200);

use includes() to check for a specific part of the URL that identifies the request or response we're interested in.



// ...

    await page.locator('text=新增').click()  
    await page.waitForResponse(response => response.url().includes('/authconfig/mgmt/roleaddingapi') && response.status() === 200);
    await page.waitForTimeout(600)
    await page.screenshot ({ path: `result.png`});

// ... 



System stability methods are essential for handling asynchronous operations that affect the whole page or application state. They help ensure that our test environment waits for these operations to complete before moving on to the next step, reducing flakiness and improving test reliability.




playwright doc

張庭瑋 Gary Chang