I tried to make an example on JavaScriptExecutor.
Test site: http://www.anaesthetist.com/mnm/javascript/calc.htm
Testing scenario: 3 + 9 = 12 (addition)
I wrote the code below, but that didn't work. I am debugging the code, I saw 12 as a result on the page, but at the statement point I got null from the .getText () method.
Here is my code:
public class CalculatorExampleTest {
static WebDriver driver;
private static String url = "http://www.anaesthetist.com/mnm/javascript/calc.htm";
@BeforeClass
public static void setupTest() {
driver = new FirefoxDriver();
driver.navigate().to(url);
driver.manage().window().maximize();
}
@Test
public void calculatorJavaScriptTest() {
WebDriverWait wait = new WebDriverWait(driver, 10);
driver.findElement(By.cssSelector("input[type='button'][onclick='AddDigit(\\'9\\')']")).click();
driver.findElement(By.cssSelector("input[type='button'][onclick='Operate(\\'+\\')']")).click();
driver.findElement(By.cssSelector("input[type='button'][onclick='AddDigit(\\'3\\')']")).click();
JavascriptExecutor js =(JavascriptExecutor)driver;
js.executeScript("Calculate();");
wait.until(textDisplayed(By.cssSelector("input[name='Display']:nth-child(1)"),"12"));
WebElement result = driver.findElement(By.cssSelector("input[name='Display']:nth-child(1)"));
assertThat(result.getText(), is("12"));
}
private ExpectedCondition<Boolean> textDisplayed (final By elementFindBy, final String text){
return new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver webDriver) {
return webDriver.findElement(elementFindBy).getText().contains(text);
}
};
}
@AfterClass
public static void quitDriver() {
driver.quit();
}
}
source
share