Selenium Remote Control For Java — A Tutorial (part 4)

One of the really cool things about Selenium Remote Control is that it gives you access to its JavaScript underpinnings using getEval. With this guy we can do something like this:

public void testGetEval()
      throws Exception
   {
      selenium.open(TEST_PAGE_URL);
      //Using some JavaScript available from Selenium
      String childSpanTextSnippet =
         " {" +
            " var tdElem = this.page().findElement('id=theLastCell'); " +
            " var tdChildSpans = tdElem.getElementsByTagName('span'); " +
            " var spanTexts = ''; " +
            " for(var i = 0; i < tdChildSpans.length; i++) { " +
            "  if(i > 0) spanTexts = spanTexts + ‘, ‘;   ” +
            ”  spanTexts = spanTexts + tdChildSpans.item(i).innerHTML; ” +
            ” }; ” +
            “spanTexts” +
            “}”;

      String texts = “row two, cell two”;
      assertEquals(texts, selenium.getEval(childSpanTextSnippet));
   }

If we place this in the test class we created in a previous tutorial and run it, we should see a green bar. Pretty cool, eh?

So, what’s going on here? Basically, we are using Selenium to execute a snippit of JavaScript. What’s more, in our snippet we can use functions defined in Selenium Core, in this case findElement. The function accepts all the different types of locators to try to find an element in the DOM. After we get the element, we do some processing, and we get the results back in Java land as a String.

We aren’t limited to using what is provided by Selenium. Consider the following:

 public void testGetEval_UsePlainJavaScript()
      throws Exception
   {
      selenium.open(TEST_PAGE_URL);

      String firstTitleSnippet =
            "{" +
            " var bodyElem = document.getElementsByTagName('title')[0]; " +
            " bodyElem.innerHTML; " +
            "}";

      assertEquals("Selenium Functional Test Runner", selenium.getEval(firstTitleSnippet));
   }

By using a snippet of JavaScript, we actually have access to the DOM of the test runner. Once again, pretty cool. With getEval we have a simple yet powerful way to extend Selenium’s functionality.

3 Responses to “ Selenium Remote Control For Java — A Tutorial (part 4) ”

  1. Блог компании IKEEN Group » Blog Archive » Вызов JavaScript из Selenium. Says:

    […] Selenium Remote Control For Java […]

  2. Angelo Says:

    Hi, i’ve tried the example’s above but i get some errors saying “illegal character” on this command “assertEquals(texts, selenium.getEval(childSpanTextSnippet));”…. please can you explain what’s wrong on it… thanks again…

  3. pjberry Says:

    @Angelo:

    If you cut and paste the code, you may be getting different characters. I know when I cut the code from here and paste back into my IDE, I get italicized formatting.

Leave a Reply