【问题标题】:Why does cypress only loop through once inside the for loop为什么 cypress 在 for 循环中只循环一次
【发布时间】:2021-09-09 00:56:09
【问题描述】:

为什么 cypress 在 for 循环中只循环一次?

测试代码是这样的:

cy.get('body').contains('Automation').each(($el, index) => {
  cy.get('body').contains('Automation').parents()
    .eq(1)
    .find('mfc-dropdown > div > mfc-button > button', { timeout: 6000 })
    .first()
    .click({ force: true });
  cy.get(this.DELETE_FILE_BUTTON).click();
  cy.get('.mfc-dialog-container')
    .find(this.CONFIRM_DELETE)
    .click({ force: true });
});

【问题讨论】:

  • 你需要正确格式化你的代码
  • 您的网页中有多少带有Automation 文字的元素?

标签: typescript for-loop automation cypress


【解决方案1】:

因为您循环的是contains 命令的结果,而contains 只返回第一个 匹配元素,而不是所有 匹配元素。见https://docs.cypress.io/api/commands/contains#Single-Element

【讨论】:

    【解决方案2】:

    @JessefSpecialisterren 给出了不发生循环的正确原因。

    你能做些什么呢?

    您可以使用:contains() pseudo-selectorcontains 移动到get()

    说明:选择包含指定文本的所有元素

    cy.get(':contains(Automation)').each(($el, index) => {
    

    您确实想直接定位元素,而不是 <body> 元素

    例如

    cy.get('button:contains(Automation)').each(($el, index) => {
    

    第 2-3 行呢?

    这看起来很可疑,我想你想要

    cy.get('button:contains(Automation)').each(($el, index) => {
      cy.wrap($el).parents().eq(1)
      ...
    

    【讨论】:

    • 谢谢你的工作!真的很感激
    【解决方案3】:

    我并没有遍历所有项目,而只是通过说来查看第一个项目

    cy.get().contains()
    

    我需要循环遍历整个列表

    cy.get('button:contains('Automation'))
    

    【讨论】:

      最近更新 更多