Search code examples
htmlseleniumscalatest

How can I verify the content of a plain text field with Selenium and Scalatest


I have a result of a PHP script

<html>
<head>
  <title>Greetings</title>
</head>
<body>
  <h1 id="header1">Hello</h1>
  <input id="input1" value="Hi" />
</body>

and want to test if all elements are filled correctly, using Selenium with Scalatest (http://www.scalatest.org/user_guide/using_selenium).

class TrialSpec extends FlatSpec with MustMatchers with HtmlUnit {
  val host = "http://localhost:8000/"
  go to (host + "index.html")

  "The homepage" should "have the correct title" in {
    pageTitle must be ("Greetings")
  }

  "The main input1" should "have the correct value" in {
    val mainInput = textField("input1").value
    mainInput must be ("Hi")
  }

  "The main header" should "have the correct content" in {
    id("header1") must be ("Hello")
  }

  quit()
}

The first two tests succeed, but I am not able to access the .firstChild or .innerHTML of the <h1> element. I also tried paragraphs and spans. What can I do?

Best Alex


Solution

  • id is a function that returns a query, not an element.

    You can use this instead:

    find(id("header1")).map(_.text) shouldBe Some("Hello")
    

    find returns Option[Element] which you can map to the text value.

    The HtmlUnit trait reference is your best source of information.