3

I tried to do an example on JavaScriptExecutor.

Test site is: http://www.anaesthetist.com/mnm/javascript/calc.htm

Test Scenario is: 3+9=12 (Addition)

I wrote below code but it did not work. I debug the code, I saw 12 as a result on the page but at assertion point I got null value from .getText() method.

Here is my code:

public class CalculatorExampleTest {
static WebDriver driver;
private static String url = "http://www.anaesthetist.com/mnm/javascript/calc.htm";

//Setup Driver
@BeforeClass
public static void setupTest() {
    driver = new FirefoxDriver();
    driver.navigate().to(url);
    driver.manage().window().maximize();
}

@Test
public void calculatorJavaScriptTest() {
    //Declare a Webdriver Wait
    WebDriverWait wait = new WebDriverWait(driver, 10);

    //1-) Click "9"
    driver.findElement(By.cssSelector("input[type='button'][onclick='AddDigit(\\'9\\')']")).click();

    //2-) Click "+"
    driver.findElement(By.cssSelector("input[type='button'][onclick='Operate(\\'+\\')']")).click();

    //3-) Click "3"
    driver.findElement(By.cssSelector("input[type='button'][onclick='AddDigit(\\'3\\')']")).click();

    //4-) Declare JavaScriptExecutor and call "Calculate()" function
    JavascriptExecutor js =(JavascriptExecutor)driver;
    js.executeScript("Calculate();");

    //driver.findElement(By.cssSelector("input[type='button'][onclick='Calculate()']")).click();

    //5-) Check result is 12?
    //Wrapped Anonymous Class (Synchronization)
    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"));

}

//Wrapped Anonymous Class
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);
        }
    };
}

//Close Driver
@AfterClass
public static void quitDriver() {
    driver.quit();
}

}

1 Answer 1

1

Since this is the input element, you need to get the value attribute value instead of text:

WebElement result = driver.findElement(By.cssSelector("input[name=Display]"));
assertThat(result.getAttribute("value"), is("12"));
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks. Problem solved. I also cross checked with Selenium IDE. Its generated code is also used getAttribute instead of getText()
I did what is written in that link. Thanks @alecxe

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.