javaplaywrightplaywright-java

Wait until element change state in Playwright with Java


I have an issue with tables. Let's say that I have a table with column and rows, I get the need to verify a value before and after

//get the value before
String randomStuff = page.locate(columnSelector).textContent() //This will give us for example Activate

// click on deactivate button
page.locate(deactivateButton).click()

// get the value after
String randomStuff = page.locate(columnSelector).textContent() //This will give us for example Deactivate

The problem is as the element exist anyway, the script give me randomly activate or deactivate, so it generate flakiness.

I have tried

page.waitForLoadState(LoadState.DOMCONTENTLOADED);
page.waitForLoadState(LoadState.NETWORKIDLE);

To wait for element to change, but nothing works.

I even waited for ready state = complete, but nothing works

String state = page.evaluate("document.readyState").toString();
outerloop:while(time<timeout) {
    try {
        Thread.sleep(200);
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
    time+=200;
    state = page.evaluate("document.readyState").toString();
    if (state.equals("complete")) 
        break outerloop;
}

I want to wait (dynamically) until the element change the state. When searching for existence or absence of an element in a table for example, tables and column exist even before the search, so Playwright doesn't wait until the table finish loading with search result.

I have many example like this in my web app, and I can't figure out a simple solution that Playwright offers.


Solution

  • You can use Awaitility (import org.awaitility.Awaitility;) with polling until your specified conditions are met. It solves most of my conditional based requirement in my app implementation.

    Callable<Boolean> wait = () -> page.locator("yourLocator").isVisible(); //you can code your condition here.
    Awaitility.waitAtMost(Duration.ofSeconds(30)).pollDelay(Duration.ofMillis(500)).until(wait);