【问题标题】:Get first element in protractor获取量角器中的第一个元素
【发布时间】:2017-01-14 11:42:13
【问题描述】:

我想验证量角器中的表格行数,在该类型表格出现多次的页面上。我一直在尝试使用 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>

还有这个量角器代码:

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

Protractor 失败的原因是有 8 个元素而不是 4 个。似乎table:first-of-type 选择器同时捕获了这两个元素,因为它们都是父级 div 组件的第一个子级。我的项目的结构是最好不要将单独的类添加到每个包装 div

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

【问题讨论】:

    标签: css-selectors protractor


    【解决方案1】:

    我没有在 Protractor 中使用 :first-of-type 作为 CSS 选择器;但是,您可以得到 first table 和所有 th,然后检查 count 是否为 4。

    expect(element.all(by.css('table')).first().all(by.css('th')).count()).toBe(4);
    

    【讨论】:

      【解决方案2】:

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

      div:first-of-type > table:first-of-type > tr:first-of-type > th
      

      我还添加了&gt; 来强制直接的父子关系

      【讨论】:

        猜你喜欢
        • 2017-03-06
        • 2015-11-30
        • 2015-03-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2017-10-06
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多