Cypress:基于另一个子元素获取父元素的子元素

3

我有两个折叠的div

<div class="collapse>
    <div class="title">Apple</div>
    <item>Apple 1</item>
    <item>Apple 2</item> // get this item
    <item>Apple 3</item>
</div>

<div class="collapse>
    <div class="title">Samsung</div>
    <item>Samsung 1</item>
    <item>Samsung 2</item>
</div>

我该如何通过类名获取项目列表,就像这样:

cy.get('.collapse').within(() => {
  if (cy.contains('.title', 'Apple') {
   cy.get(item).eq(1).... // handle item second of apple
  }
});

1
你的HTML在第一和第二部分有两个未关闭的div,请修正它。 - Alapan Das
1个回答

2
您可以通过子元素的内容来指定所需的 .collapse
cy.contains('.collapse', 'Apple')  // gets the 1st collapse element where child has "Apple" text
  .find('item').eq(1)             // within that, get the 2nd <item>
  .should('have.text', 'Apple 2')

如果您的实际HTML更为复杂,且想要从标题元素开始,请使用以下代码:
cy.contains('.title', 'Apple')  // get the title child with "Apple" text
  .parent()                    // move up to div.collapse
  .find('item').eq(1)         // within that, get the 2nd <item>
  .should('have.text', 'Apple 2')

或兄弟导航
cy.contains('.title', 'Apple')  // get the tile child with "Apple" text
  .siblings('item').eq(1)       // 2nd item sibling
  .should('have.text', 'Apple 2')

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接