Chandrachud Nanduri
Chandrachud Nanduri

Reputation: 111

getText() returns empty string after sendKeys()

I have a class with the following public instance variable

@FindBy(id="titleInput")
public WebElement titleInputBox;

Then I use page factory in the constructor to initialize it on every use

PageFactory.initElements(driver, this);

In my test case for this page, I use the following code to test whether the text I sent is actually getting set in the field ...

subtitleInputBox.sendKeys("Test");
subtitleInputBox.getText();

and I get empty string

any idea why this happens ... I think it works fine if driver.findElement() is used directly without @FindBy and PageFactory

Upvotes: 4

Views: 2118

Answers (2)

Saurabh Gaur
Saurabh Gaur

Reputation: 23805

Actually WebElement.getText() returns the visible (i.e. not hidden by CSS) innerText of this element, including sub-elements, without any leading or trailing whitespace while you need input box element value attribute text.

FYI input box element stores the text which you are trying to set using WebElement.sendKeys() into their attribute name value instead of inner text.

So you should try using WebElement.getAttribute() which to be used to get the value of a the given attribute of the element.

Here you need to implement WebDriverWait also to determine whether element value has been successfully set or not using ExpectedConditions.textToBePresentInElementValue as below :-

subtitleInputBox.sendKeys("Test");

//Now wait until value has been set into element 
new WebDriverWait(driver, 10).until(ExpectedConditions.textToBePresentInElementValue(subtitleInputBox, "Test"));

//Now get the element value
subtitleInputBox.getAttribute("value");

Upvotes: 2

Grasshopper
Grasshopper

Reputation: 9058

To get the text out of an input box like text or textarea you need to use the getAttribute("value") method. getText() works for tags like div, span etc etc.

subtitleInputBox.getAttribute("value");

Upvotes: 4

Related Questions