gpt4 book ai didi

javascript - 通过 cypress.get() 选择 HTML 中的元素

转载 作者:行者123 更新时间:2023-11-28 04:28:17 28 4
gpt4 key购买 nike

我正在使用 cypress针对 html 站点编写一些测试..

下面我选对了一个tr我的 HTML 网站上表格中的元素。站点内容如下所示:

<tr data-recordid="theId">
<td...><div ..>Text 1</div></td>
<td...><div ..>Text 2</div></td>
<td...><div ..>Text 3</div></td>
</tr>

以下测试脚本片段正确地选择了单个 <tr..>部分。

cy.get('tr[data-recordid="theId"]').contains('Text')

现在我想选择 <div>..</div> 中的文本标签..我尝试为第一个 <div>..</div> 链接单个调用的第一件事像这样的标签:

cy.get('tr[data-recordid="theId"]').get('div').contains('Text')

这并没有像我预期的那样工作。 get()调用链式 jQuery 调用(基于 Cypress 文档)。所以看起来我误解了 JQuery 中的工作原理。

我期待的是如何检查所有 div 元素(不工作):

cy.get('tr[data-recordid="theId"]')..SomeHowMagic
.get('td[alt="xyz"]".get('div').contains('Text 1')
.get('td...').get('div').contains('Text 2')
.get('td...').get('div').contains('Text 3')

知道如何向前迈出一步吗?缺少任何信息,请发表评论。

最佳答案

让我们澄清一些事情:

1) 如果您只是想断言 div 包含给定的文本,那么这是执行此操作的最佳和最精确的方法:

cy.get('tr[data-recordid="theId"]').should(($tr) => {
const $divs = $tr.find('div') // find all the divs

expect($divs.eq(0)).to.contain('Text 1')
expect($divs.eq(1)).to.contain('Text 2')
expect($divs.eq(2)).to.contain('Text 2')
})

我不知道事情是否需要如此具体。如果您只想确保 $tr 包含文本,您可以将其简化为:

cy.get('tr[data-recordid="theId"]').should(($tr) => {
expect($tr).to.contain('Text 1')
expect($tr).to.contain('Text 2')
expect($tr).to.contain('Text 2')
})

为什么要这样做?

  • 使用.should() 函数不会改变主题。您的 $tr 将继续成为 future 的主题。
  • Cypress 将等待 .should() 回调中的所有断言都通过,并不断重试直到它们通过。这保证您在继续之前多个元素的状态是正确的。

2) 但是,如果您只关心 Cypress 找到文本而不介意更改主题,您可以这样做:

cy.get('tr[data-recordid="theId"]').within(() => {
cy.contains('Text 1') // changes the subject to the <div>
cy.contains('Text 2') // changes the subject to the <div>
cy.contains('Text 3') // changes the subject to the <div>
})

这与第一个示例不同,因为您只是将主题更改为找到文本的任何元素,而不是显式断言。 Cypress 对 cy.contains() 的默认断言是重试所以最终行为是一样的,除了你另外改变了主题。

如果这太复杂了,你也可以这样做:

cy.get('tr[data-recordid="theId"] div').contains('Text 1')
cy.get('tr[data-recordid="theId"] div').contains('Text 2')
cy.get('tr[data-recordid="theId"] div').contains('Text 3')

您的原始问题还使用了链式 cy.get(),它不会深入研究主题。为此,请使用 .find()

cy.get('a').get('span') // each cy.get() queries from the root
cy.get('a').find('span') // the .find() queries from the <a>

最后一点:您建议的解决方案无效。 cy.get() 不接受回调函数,如果您查看命令日志,您将看不到这 3 个 cy.contains 被调用过。换句话说,它们没有运行。这就是它通过的原因。

关于javascript - 通过 cypress.get() 选择 HTML 中的元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46512559/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com