Cypress 迭代表行获取单元格中的特定元素

问题描述 投票:0回答:3

我正在尝试迭代表行并获取包含特定值的每一行, 但这对我不起作用。 我使用

.each()
迭代行,并使用
.within()
迭代每个
$el
, 在其中,我使用
cy.get('td').eq(1).contains('hello')
但我得到断言错误:

超时重试:期望在元素中找到内容:“hello”:

<td>
但从未找到。

当我console.log

cy.get('td').eq(1)
时,它会在每行中生成所需的单元格并且测试通过,所以我不明白为什么链接
.contains()
不起作用...

it('get element in table', () => {
  cy.visit('http://localhost:3000/');
  cy.get('tbody tr').each(($el) => {
    cy.wrap($el).within(() => {
      cy.get('td').eq(1).contains('hello') // contains() doesn't work
    })
  })
});
<table>
  <thead>
    <tr>
      <th>Month</th>
      <th>Savings</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>January</td>
      <td>$100</td>
    </tr>
    <tr>
      <td>February</td>
      <td>hello</td>
      <td>$80</td>
    </tr>
     <tr>
      <td>$10</td>
      <td>hello</td>
    </tr>
  </tbody>
</table>

javascript cypress
3个回答
3
投票

should('have.text', text)
应该可以工作

cy.get('td').eq(1).should('have.text', 'hello')

如果文本周围有空格,请使用

contain.text

cy.get('td').eq(1).should('contain.text', 'hello')

0
投票

这对我有用:

      cy.get("table")
        .find("tbody")
        //Iterate through the rows
        .each(($row, $index) => {
          cy.wrap($row).within(() => {
            cy.get("td")
              .eq(1) // Second column
              .invoke("text")
              .then((text) => {
                if (text.includes("the-text-i-want")) {
                  cy.get("td")
                    .eq(1)
                    .contains("the-text-i-want");
                } else {
                  cy.log("Skipping");
                }
              });
          });
        });

-2
投票

简单的答案是:不要:)

更具体地说,请使用 html 属性选择。约定是有一个名为

data-cy
的属性。此外,我发现在选择特定行时使用
data-cy-identifier
很方便。由于我不确定您正在尝试使用代码做什么,因此我将使用一个类似的示例,希望可以帮助您继续:

<table data-cy="expences">
    <tr>
        <td data-cy="month">January</td>
        <td data-cy="price">$100</td>
    </tr>

    <tr data-cy="discounted">
        <td data-cy="month">Feburary</td>
        <td data-cy="price">$80</td>
    </tr>

    <tr data-cy="discounted">
        <td data-cy="month">March</td>
        <td data-cy="price">$10</td>
    </tr>
</table>

您当然可以进行各种组合,但现在您可以进行更具体和有用的选择,例如:

cy.get('[data-cy="expenses"]').find('[data-cy="discounted"]').find('[data-cy="price"]').should(...)

类似。这是灵活的,因为它反映了数据的结构,而不是表示形式,因此您可以稍后将其更改为列表或其他内容。它避免了选择不稳定的东西,所以它也更健壮。它还使用层次结构而不是过于具体的选择器。

添加诸如

data-cy-identifier
之类的内容的想法允许您通过 ID 进行选择(您可以使用 javascript、Angular、Vue 或任何您使用的内容来传播它),然后检查诸如具有逻辑相关项的行内容之类的内容。

希望它能帮助你前进。我还可以推荐阅读:https://docs.cypress.io/guides/references/best-practices.html

© www.soinside.com 2019 - 2024. All rights reserved.