0 votes
1 view
in Devops and Agile by (19.8k points)

I am writing Test Cases using Selenium web Driver in TestNG and I have a scenario where I am running multiple tests sequentially (refer below)

@Test(priority =1)

public void Test1(){

}

@Test(priority =2)

public void Test2(){ 

}

Both Tests are AJAX calls where a Dialog box opens, tests execute, then dialog box closes and then a notification message appears on top of the page and after each successful test, the page refreshes.

The problem is: Test2 does not wait for the page to refresh/reload. Suppose when Test1 gets successfully completed, Test2 will start before page refresh (ie it opens the dialog box, executes scenarios, etc..) meanwhile the page refreshes (which was bound to happen after successful execution of Test1 ). Now since the page refreshes, the dialog box opened due to Test2 is no longer present and then Test2 fails.

(Also, I do not know how long it will take to refresh the page. Therefore, I do not want to use Thread.sleep(XXXX) before executing Test2)

Also, I don't think

driver.navigate().refresh()

will solve my problem by putting it before Test2 as in that case my page will get refreshed twice. The problem is the refresh that is happening through the code (which is uncertain as it may take 1 sec or 3 sec or 5 sec)

1 Answer

0 votes
by (63.4k points)

Use the code below:

import org.openqa.selenium.JavascriptExecutor;

import org.openqa.selenium.WebDriver;

import org.openqa.selenium.firefox.FirefoxDriver;

import org.openqa.selenium.support.ui.ExpectedCondition;

import org.openqa.selenium.support.ui.WebDriverWait;

import org.testng.Assert;

public class Tutorials {

    WebDriver driver = new FirefoxDriver();

    public void waitForPageLoaded() {

        ExpectedCondition<Boolean> expectation = new

                ExpectedCondition<Boolean>() {

                    public Boolean apply(WebDriver driver) {

                        return ((JavascriptExecutor) driver).executeScript("return document.readyState").toString().equals("complete");

                    }

                };

        try {

            Thread.sleep(1000);

            WebDriverWait wait = new WebDriverWait(driver, 30);

            wait.until(expectation);

        } 

           catch (Throwable error) {

              Assert.fail("Timeout waiting for Page Load Request to complete.");

        }

    }

}

Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...