Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get first element in protractor

I want to verify the number of table rows in protractor, on a page in which tables of this type appear more than once. I've been trying to use the first-of-type selector, but it seems to be catching both tables because they do not appear side by side.

For example, given this HTML:

<div>
  <table class="foo">
    <tr>
      <th>First row</th>
      <th>Second row</th>
      <th>Third row</th>
      <th>Fourth row</th>
    </tr>
  </table>
</div>
<div>
  <table class="foo">
    <tr>
      <th>First row</th>
      <th>Second row</th>
      <th>Third row</th>
      <th>Fourth row</th>
    </tr>
  </table>
</div>

And this protractor code:

element.all(by.css('table:first-of-type tr:first-of-type th')).then(function (elements) {
  expect(elements.length).toBe(4);
});

Protractor is failing on the grounds that there are 8 elements and not 4. It seems the table:first-of-type selector is catching both elements, since they're both the first children of their parent div components. My project is structured in such a way that it's better not to add individual classes to each wrapping div.

Is there a way to get the first element found in Protractor and then search its child elements?

like image 439
A. Duff Avatar asked Dec 23 '22 21:12

A. Duff


1 Answers

I have not used :first-of-type as a css selector in Protractor; however, you could get the first table with all th's and then check to see if the count is 4.

expect(element.all(by.css('table')).first().all(by.css('th')).count()).toBe(4);
like image 59
cnishina Avatar answered Dec 29 '22 08:12

cnishina