Vladyslav Nikonov
Vladyslav Nikonov

Reputation: 11

How to choose last element and verify his attribute

I wrote a test where the user sends a message to another. I need to choose every time last message that was sent and verify his attribute value.

    driver.findElement(By.xpath("//*[@id=\"chatView\"]/div/div[1]/div[1]")).sendKeys("Hello SMS");

    driver.findElement(By.xpath("//*[@id=\"chatView\"]/div/div[1]/div[1]")).sendKeys(Keys.ENTER);

    List<WebElement> webElements = driver.findElements(By.id("messagesContainer"));

    WebElement lastElement = getLast.driver.findElement(By.className("message-item"));

    System.out.println(lastElement);

    System.out.println(lastElement.getAttribute("data-deliverystatus"));

Upvotes: 1

Views: 1890

Answers (2)

Guy
Guy

Reputation: 50899

findElements(By.id("messagesContainer")) will return you list of one element, the parent element of the messages. If you want the messages you need to use

List<WebElement> messages = driver.findElements(By.className("message-item"));

To get the last one use the index of list size minus 1

List<WebElement> messages = driver.findElements(By.className("message-item"));
WebElement lastMessage = messages.get(messages.size() - 1);
Assert.assertEquals(lastMessage.getAttribute("data-deliverystatus"), "sent");

Upvotes: 3

David Baak
David Baak

Reputation: 934

You can use the size of the list minus one.

List<WebElement> webElements = driver.findElements(By.id("messagesContainer"));

WebElement lastElement = webElements.get(webElements.size() - 1)); 

// example test in testng, expecting SENT
Assert.assertEquals(lastElement.getAttribute("data-deliverystatus"), "SENT");

Upvotes: 0

Related Questions