Vladislav Belousov
Vladislav Belousov

Reputation: 101

Wait for network idle after click

I'm looking for a method that would allow me to wait for the network idle after clicking a button or some action. there is a way to wait for the network idle after clicking? page.locator("text=Click").click() //some method that wait network is idle after clicking the button

I tried waitForLoadState works only if there is navigation. waitForResponse works on specific requests but it's not good for me.

Upvotes: 10

Views: 32224

Answers (6)

OLEG ACULOV
OLEG ACULOV

Reputation: 11

await Promise.all([ page.waitForNavigation({waitUntil:"networkidle"}) , page.locator("text=Click").click() ])

Upvotes: 1

Vishal Aggarwal
Vishal Aggarwal

Reputation: 4207

I think combining wait for response with some visible UI change after fetch request will help:

await button.click() 
await page.waitForResponse(res => res.status() === 200) 

const newText = await page.getByRole('paragraph') 
const newImage = await page.getByRole('img')
 
await expect(newText).not.toEqual(prevText) 
await expect(newImage).not.toEqual(prevImage) 

Upvotes: 0

Consider using waitForResponse if you know what particular network communication you're initiating with the button click and thus know what URLs you can use to monitor the requests/responses of to see if the communication has finished yet.

https://playwright.dev/docs/api/class-page#page-wait-for-response

For example:

// Click the *Delete* button
await page.getByText('Delete').click();

// Wait for the `api/items/delete` endpoint to be called
await page.waitForResponse(/\/api\/items\/delete/);

Unfortunately this won't cover the scenario of waiting after all network activity settles after the button click.

Upvotes: 3

gabo
gabo

Reputation: 3

You could try page.waitForTimeout(milliseconds) and just give it a wait value for safety. It helped me is some cases to increase the waiting time where the test was going to timeout 5000ms because of the loading time.

Upvotes: -1

alfah
alfah

Reputation: 135

There is a playwright library for network idle wait.

await page.waitForLoadState('networkidle')

I hope this helps you.

Upvotes: 7

AutomationAndy
AutomationAndy

Reputation: 992

As your use case is to click a link which dynamically loads in other DOM Elements, you could possibly try using .waitForSelector().

page.locator("text=Click").click()
page.waitForSelector('selector for what you are waiting for here')

Also pass options to waitForSelector to wait for it being attached and / or visible and setTimeout appropriately.

I was going to suggest using assertion polling but I don't believe the Java version of playwright has that yet.

Upvotes: 1

Related Questions