Javascript 为什么Cypress';在';函数仅搜索第一个子项而不是所有子项?

Javascript 为什么Cypress';在';函数仅搜索第一个子项而不是所有子项?,javascript,cypress,Javascript,Cypress,我的网站上有以下HTML结构: <body> ... <div class="main-wrapper"> <div class="first-child"> <p>elements belonging to first-child</p> </div> <div class="second-child">

我的网站上有以下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>
显然,Cypress只能找到
.first child
元素,而不能找到
.second child
元素。 但是我不明白为什么Cypress中的
中的
只能处理第一个子元素,而不能处理作用域元素中的所有子元素

如果我在
块中删除
,并将它们放在全局范围内,则Cypress在查找它们时没有问题,如下所示:

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!
});
   cy.get('.first-child p').click();
   cy.get('.second-child p').click();
我应该如何在
中使用
,以便Cypress可以找到作用域元素中的所有子元素,而不仅仅是第一个子元素

编辑:


再想一想,我不确定这是否会影响
的工作方式,但是
。第二个子
实际上只会在单击
。第一个子
后插入DOM。在我的例子中,
.first child
确实是首先被单击的,因此我假设DOM已经有了
。当Cypress尝试查找
。second child
时,second child
,对吗?

如果您运行这个基本测试,其中
.second
是在页面加载3秒后添加的,找到添加的
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

您可以指定当单击控制台输出时,
中的
返回到控制台输出的内容吗?@AlexIzbas当我单击输出时,我在控制台中得到这个信息:
断言错误:超时重试:预期会找到元素:“div.second-child p”,但从未找到它。
这看起来是
cy.get('.second child p')
的输出。尝试包装上一个生成的主题:
cy.get('.main wrapper')。在($el)=>{…}
并在
命令中检查cypress日志中的
,并检查它在控制台中包装/返回的元素。让我们确保它同时返回这两个元素elements@AlexIzbas我将该行包装在
内的
回调中。当我单击
内的
命令时,输出显示它产生了
@AlexIzbas我没有当然,如果这会影响
中的
命令的工作方式,但是
.second child
实际上只会在单击
.first child
之后插入到DOM中。在我的情况下,
.first child
确实是首先被单击的,但我开始认为Cypress可能没有意识到DOM已经被删除了更新?