Jacob
Jacob

Reputation: 1225

How to wait for JavaScript to finish in playwright

I am testing UI with Playwright and JavaScript. My code find an input element that can sometimes be a drop down, sometimes a text and sometimes a date. To handle this I enter value with 2 steps. First I fill the text and then click on tab key to invoke the JavaScript that formats the value in the element.

await page.fill("#myID", inputText); 
await page.keyboard.press('Tab');  // this line trigger the JS

// continue to the next element 

The problem, it is not waiting for JavaScript to finish. How can I wait for JS to finish before the code continue.

Upvotes: 16

Views: 59850

Answers (3)

Vishal Aggarwal
Vishal Aggarwal

Reputation: 4177

You can use waitForFunction here:

To ensure that your JavaScript has finished executing after you press the 'Tab' key, you can use page.waitForFunction to wait for a specific condition to be true. This can be the presence of a formatted value or any other indication that the JavaScript has completed.

You can modify your code like below:

// Fill the text input
await page.fill("#myID", inputText);

// Press 'Tab' key to trigger JavaScript
await page.keyboard.press('Tab');

// Wait for the JavaScript to finish
await page.waitForFunction(() => {
    const element = document.querySelector("#myID");
    return element && element.value.includes("formatted value"); // Update this line based on your specific condition
}, { timeout: 5000 });

// Continue to the next element

Upvotes: 0

dst
dst

Reputation: 211

You could wait for some reaction to your click (some page change, or HTTP request made), for example:

Upvotes: 16

Steve
Steve

Reputation: 10886

Using the page.waitFor... functions

There are a slew of functions that playwright offers for when certain conditions are met that start with page.waitFor (e.g. page.waitForFunction). Probably page.waitForFunction is the most versatile, because you can pass a custom function that waits for a specific condition to be met.

Alternatively, use a timeout

I think you can use setTimeout with page.evaluate inside the page context to wait a bit for other JavaScript to run:

await page.evaluate(() => {
  // if this doesn't work, you can try to increase 0 to a higher number (i.e. 100)
  return new Promise((resolve) => setTimeout(resolve, 0));
});

This might be equivalent to page.waitForTimeout(0), but I'm not sure. Note that they recommend not to use page.waitForTimeout in production.

Upvotes: 12

Related Questions