【发布时间】: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) => { ... }并检查 cypress 日志中的within命令并检查它在控制台中包装/返回的元素。让我们确保它返回两个元素 -
@AlexIzbas 我在
within回调中包裹了一行。当我点击within命令时,输出显示它产生了<div class="main-wrapper"><div class="first-child">...</div></div> -
@AlexIzbas 我不确定这是否会影响
within命令的工作方式,但.second-child实际上只会在单击.first-child后插入到DOM 中。就我而言,.first-child确实首先被点击,但我开始认为赛普拉斯可能不知道 DOM 已更新?
标签: javascript cypress