如何在 cypress 中链接 cy.get

use*_*310 2 javascript java css-selectors ui-automation cypress

我试图到达 #1 元素,然后到达 #2 元素以单击 #3 元素

但我在 Cypress 中获取正确的 CSS 选择器时遇到了麻烦。

在此输入图像描述

如何为此编写测试脚本?

我已经尝试过 cy.get('.ui.active.visible.button.floating.dropdown.fr-dropdown').contains('Delete yield').click()但不起作用。

有没有办法先获得#1,然后#2 到达#3?这不是真正的代码,而是类似这样的代码。

cy.get('.yield-event__date-and-text--container').contains('10kg')
cy.get('.ui.active.visible.button.floating.dropdown.fr-dropdown').click()
cy.get('.item.fr-dropdown__option').contains('Delete yield').click()
Run Code Online (Sandbox Code Playgroud)

预先非常感谢

Ala*_*Das 7

您可以使用find()编写类似的内容:

cy.get('.yield-event__date-and-text--container').contains('10kg')
cy.get('.yield-event__date-and-text--container').find('i[class*="fr-dropdown__icon"]').click({force: true})
cy.get('.yield-event__date-and-text--container').find('Delete yield').click({force: true})
Run Code Online (Sandbox Code Playgroud)


Ack*_*ydd 5

正如 @RosenMihaylov 所说,您可能会发现使用遵循 HTML 结构的 Cypress“关系”命令比 CSS 选择器更容易。

另外,我认为您需要单击两次 - 第一次打开菜单,第二次调用删除操作。

第 1 步 - 看起来文字devEnv_admin标识了您想要的卡

cy.contains('div', 'devEnv_admin')
Run Code Online (Sandbox Code Playgroud)

这给了你第七个格。

第 2 步 - 您需要单击的下拉菜单是上述下拉菜单的第二个同级菜单

.siblings('div.note-event__dropdown')  // list of siblings matching the selector
.eq(0)                                 // take the first (and only)
Run Code Online (Sandbox Code Playgroud)

这为您提供了下拉按钮的父级。

第 3 步 - 但看起来具有类的子元素button可能具有单击事件处理程序(您可能必须在这里进行实验,因为具有事件处理程序的元素有时很难找到)

.children('div.button')   // list of children matching the selector
.eq(0)                    // take the first (and only)
.click();
Run Code Online (Sandbox Code Playgroud)

应该打开菜单,但可能需要几毫秒才能出现

第 4 步 - 等待包含您需要的文本的 div

cy.contains('span', 'Delete yield')   // this form of .contains() waits for the text
  .click();
Run Code Online (Sandbox Code Playgroud)

总之,

cy.contains('div', 'devEnv_admin')
  .siblings('div.note-event__dropdown')  // list of siblings matching the selector
  .eq(0)                                 // take the first (and only)
  .children('div.button')                // list of children matching the selector
  .eq(0)                                 // take the first (and only)
  .click();

cy.contains('span', 'Delete yield')   // this form of .contains() waits for the text
  .click();
Run Code Online (Sandbox Code Playgroud)

您还可以使用 DOM 元素和其他选择器的其他路径,例如.next().parent()

很大程度上取决于事件处理程序的附加位置,通过查看源代码最容易找到这一点。


或者,使用within()

cy.contains('.yield-event__date-and-text--container', 'devEnv_admin')  // pick the card
  .within(() => {  // restricts commands below to this card
    cy.get('div.button.dropdown').click();
    cy.contains('span', 'Delete yield').click();
  });
Run Code Online (Sandbox Code Playgroud)