【问题标题】:Why does Cypress 'within' function only search the first child but not all children?为什么赛普拉斯的“内部”功能只搜索第一个孩子而不是所有孩子?
【发布时间】:2020-06-24 11:28:58
【问题描述】:

我的网站上有以下 HTML 结构:

<body>
 ...
 <div class="main-wrapper">
   <div class="first-child">
      <p>elements belonging to first-child</p>
   </div>
   <div class="second-child">
      <p>elements belonging to second-child</p>
   </div>
 </div>
</body>

我正在尝试使用赛普拉斯的within 函数来确定.main-wrapper 类的范围。 所以,我有这样的事情:

cy.get('.main-wrapper').within(() => {
   cy.get('.first-child p').click();      // Cypress can find this
   cy.get('.second-child p').click();     // Cypress cannot find this!
});

显然,赛普拉斯只能找到 .first-child 元素,但不能找到 .second-child 元素。 但我不明白为什么 Cypress 中的 within 只能与第一个子元素一起使用,而不能与作用域元素中的所有子元素一起使用。

如果我删除 within 块并将它们放在全局范围内,赛普拉斯可以毫无问题地找到它们,如下所示:

   cy.get('.first-child p').click();
   cy.get('.second-child p').click();

我应该如何使用within 以便赛普拉斯可以找到作用域元素中的所有子元素,而不仅仅是第一个子元素?

编辑:

再想一想,我不确定这是否会影响within 的工作方式,但.second-child 实际上只会在单击.first-child 后插入到DOM 中。在我的例子中,.first-child 确实是首先被点击的,所以我假设在赛普拉斯试图寻找 .second-child 时,DOM 已经有了 .second-child,对吧?

【问题讨论】:

  • 您能否指定单击within 时返回到控制台输出的内容?
  • @AlexIzbas 当我点击输出时,我在控制台中得到了这个:AssertionError: Timed out retrying: Expected to find element: 'div.second-child p', but never found it.
  • 这看起来是cy.get('.second-child p') 的输出。尝试包装先前产生的主题:cy.get('.main-wrapper').within(($el) =&gt; { ... } 并检查 cypress 日志中的 within 命令并检查它在控制台中包装/返回的元素。让我们确保它返回两个元素
  • @AlexIzbas 我在within 回调中包裹了一行。当我点击within 命令时,输出显示它产生了&lt;div class="main-wrapper"&gt;&lt;div class="first-child"&gt;...&lt;/div&gt;&lt;/div&gt;
  • @AlexIzbas 我不确定这是否会影响within 命令的工作方式,但.second-child 实际上只会在单击.first-child 后插入到DOM 中。就我而言,.first-child 确实首先被点击,但我开始认为赛普拉斯可能不知道 DOM 已更新?

标签: javascript cypress


【解决方案1】:

如果您在页面加载后 3 秒添加 .second 的情况下运行此基本测试,则会找到添加的 div.second-child

HTML 片段

<div class="main-wrapper">

  <div class="first-child">
    <p>elements belonging to first-child</p>
  </div>

</div>

<script>
  setTimeout(() => {

    const wrapper = document.querySelector('.main-wrapper');
    let second = document.createElement("div");
    second.classList.add('second-child')
    wrapper.appendChild(second)

  }, 3000);    // wait within the limit of Cypress' timeout
</script>

测试

it('', ()=> {

  cy.visit('app/within.html')

  cy.get('.main-wrapper').within(() => {
    cy.get('.first-child')
    cy.get('.second-child')  // succeeds
  });
  
})

在我看来,问题出在.first-child 的点击处理程序中。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-07
    • 1970-01-01
    • 2017-03-11
    相关资源
    最近更新 更多