首页 > 解决方案 > 在 Cypress 中正确链接选择器

问题描述

我已经与赛普拉斯合作了几个星期,我开始需要更复杂的选择。现在我无法理解如何链接选择器来获得我需要的东西。

这是我正在查看的 HTML 的简化版本:

<my-application-list-item test-hook="applicationListItem">
  <div>
    <!---->
    <div>
      <header>
        <a test-hook="name" href="/build/applications/iVANKl9Z">E2E Test Item</a>
        <my-build-application-menu>
          <!---->
          <my-dropdown testhook="actionsMenu">
            <my-icon-button-settings testhook="openActionsMenu">
              <button testhook="openActionsMenu">

测试钩子是在我们使用 Protractor 时放置的,断字不一致。但无论如何,我想找到并单击其中包含可见文本“E2E 测试项目”的openActionsMenu那个。applicationListItem

根据、 和的文档get,我认为这会起作用:containsfind

cy.get('[test-hook="applicationListItem"]')
  .contains("E2E Test Item")
  .find('[testhook="openActionsMenu"]')

但这导致

Timed out retrying after 4000ms: Expected to find element: [testhook="openActionsMenu"], but never found it. Queried from element: <a.ellipsis.my-info-box__title-link.my-link>

即使跑步

cy.get('[testhook="openActionsMenu"]')

成功。我究竟做错了什么?

标签: css-selectorscypress

解决方案


使用.contains(selector, content)contains() 的形式。

传下来的主题是匹配的selector

cy.contains('[test-hook="applicationListItem"]'), "E2E Test Item")
  .find('[testhook="openActionsMenu"]')

做一点实验,.then(console.log)用来检查那个时候的主题

cy.contains('[test-hook="applicationListItem"]'), "E2E Test Item")
  .then(subject => console.log(subject)    // <my-application-list-item>
  .find('[testhook="openActionsMenu"]')
  .then(subject => console.log(subject)    // <my-icon-button-settings>

推荐阅读