Tutorial 11 – Explicit timeouts in Playwright Java
What you will Learn in this blog:
Explicit Timeout in Playwright Java
Code snippets
Explicit Timeout in Playwright Java
In the previous article we had seen how to setup global default timeout.
Let us now see how to setup explicit timeout for a specific element in playwright-java.
Launch http://uitestingplayground.com/ajax
Read the scenario description that says “after we press the button, the ajax data will appear after 15 seconds”. Thus the wait time here is 15 seconds
This means that, on clicking the button, the ajax data gets loaded after 15 seconds
Inspect the button
Inspect the AJAX data. We can identify the AJAX data using the class ‘bg-success’ or by the text ‘Data loaded with AJAX get request’
Below is the snippet from our previous article. Let us comment default timeout (line#18)
We will now set the explicit wait timeout. The idea here is that, before we fetch the innertext of output ajax data (line#24 seen above), we will first wait explicitly for the output ajax data viz
Once the data gets loaded, we will fetch the innertext.
There is a ‘waitForSelector() method that accepts 2 arguments: the selector and the timeout
The selector argument will basically hold the locator of ajax data output (since this is the element we want to wait for)
The syntax of second argument (viz timeout) is as shown below. Let us set the timeout of 16 seconds
So our code looks like below
Save and execute the test.
As expected, the test will pass and the ajxmsg gets printed in the console
Let us now comment 16sec timeout and add 14sec timeout as shown below
Save and execute.
The test fails this time because the ajax data gets loaded only after 15 seconds, however we have setup timeout of 14 seconds
So this is how the explcit timeout on a specific element works.
Code snippet
package com.w2a.pwjava;
import com.microsoft.playwright.Browser;
import com.microsoft.playwright.BrowserContext;
import com.microsoft.playwright.BrowserType;
import com.microsoft.playwright.Page;
import com.microsoft.playwright.Playwright;
public class ExplicitWaitPW {
public static void main(String[] args) {
Playwright pw = Playwright.create();
Browser browser = pw.chromium().launch(new BrowserType.LaunchOptions().setHeadless(false));
BrowserContext browserContext = browser.newContext();
Page page = browserContext.newPage();
//page.setDefaultTimeout(16000); //test passes
page.navigate("http://uitestingplayground.com/ajax");
page.locator("text=Button Triggering AJAX Request").click();
//set explicit timeout
//page.waitForSelector(".bg-success", new Page.WaitForSelectorOptions().setTimeout(16000));//test passes
page.waitForSelector(".bg-success", new Page.WaitForSelectorOptions().setTimeout(14000));//test fails
String ajxmsg = page.locator(".bg-success").innerText();
System.out.println(ajxmsg);
}
}
Thanks for reading!