获得量角器中的第一个元素

A. *_*uff 4 css-selectors protractor

我想在一个页面中验证量角器中的表行数,在该页面中,此类表格不止一次出现.我一直在尝试使用first-of-type选择器,但它似乎正在捕捉两个表,因为它们不会并排显示.

例如,给定此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>
Run Code Online (Sandbox Code Playgroud)

而这个量角器代码:

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

量角器失败的原因是有8个元素而不是4个.看起来table:first-of-type选择器捕获了两个元素,因为它们都是它们父div组件的第一个子元素.我的项目结构是这样的,最好不要在每个包装中添加单个类div.

有没有办法获得在Protractor中找到的第一个元素,然后搜索其子元素?

cni*_*ina 5

我没有:first-of-type在Protractor中用作css选择器; 但是,你可以得到的第一个 table与所有th的,然后检查,看看是否计数为4.

expect(element.all(by.css('table')).first().all(by.css('th')).count()).toBe(4);
Run Code Online (Sandbox Code Playgroud)


ale*_*cxe 5

你当然可以按照@cnishina建议的方式来做(实际上我更喜欢他的方法而不是制作一个长的CSS选择器),但是如果你想继续使用单个CSS选择器来解决这个问题,你还应该将(first-of-type或first-child)应用于家长div:

div:first-of-type > table:first-of-type > tr:first-of-type > th
Run Code Online (Sandbox Code Playgroud)

我还添加了>来强制执行直接的父子关系。