[FIXED] Can I test on the order of elements using Selenium Webdriver?

Issue

There is a form in which there are 3 fields with 3 different ID’s:

<fieldset>
<div><label for="field1">
 FIELD1
 </label>
 <textarea id="field1" name="field1" rows="10" cols="40"></textarea></div>


 <div><label for="field2">
  FIELD2
</label><textarea id="field2" name="field2" rows="10" cols="40"></textarea></div>


<div><label for="field3">
  FIELD3
</label><textarea id="field3" name="field3" rows="10" cols="40"></textarea></div>

</fieldset>

Now, there is a Story in our scrum process which places FIELD3 at the top of the page, above FIELD1, so that the new order of fields will be 3, 1, 2.

My question is: Is there a way to verify/assert the order? If yes, how do I test this automatically using Selenium Webdriver (java)?

Solution

You sure can. Here’s some pseudo-code.

assertTrue(
    driver.findElement(
        By.cssSelector("div#parent > div:nth-child(1) > textarea#field3")
    ).isDisplayed()
);

The logic here pretty much says:

Look for the first div that is under <div id="parent">, that is immediately followed by <textarea id="field3">. If this assertion fails, that means it’s out of order, and the third field is NOT first.

(note, that div#parent is obviously subject to change. You need to change it to the parent of these divs, and you may also need to fiddle about with the :nth-child(n) depending on the order)

Answered By – ddavison

Answer Checked By – Pedro (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published