识别 cypress 中的 web 元素

identifying the web element in cypress

我对 java 脚本和 cypress 网络自动化还很陌生。我一直在尝试自动化一个练习站点,但我一直在为网页中的以下按钮寻找元素定位器。有人可以帮我如何为下面的网络元素创建一个 cssSelector 吗?附上html。页面中有 2 个登录按钮。我想唯一标识第一个登录按钮。粘贴在 html 示例下方:

<div _ngcontent-oxt-c19="" class="offset-sm-3 col-sm-9"><button _ngcontent-oxt-c19="" nbbutton="" status="primary" type="submit" _nghost-oxt-c16="" ng-reflect-status="primary" class="appearance-filled size-medium status-primary shape-rectangle transitions" aria-disabled="false" tabindex="0" css="1">Sign in</button></div>

<button _ngcontent-oxt-c19="" nbbutton="" status="primary" type="submit" _nghost-oxt-c16="" ng-reflect-status="primary" class="appearance-filled size-medium status-primary shape-rectangle transitions" aria-disabled="false" tabindex="0" css="1">Sign in</button>

使用:

cy.contains("Sign in");

这将在当前文档中搜索带有文本“登录”的元素。另一个最佳实践是告诉您的开发人员始终尝试为要测试的特殊元素添加 data-testid="uniqueId",这种添加 data-testid 的模式将有助于保持此类 elementLocator 未被删除(因为每个人都知道此属性用于仅限测试人员)

从你的示例中我可以看出两个 buttons 是相同的,除了一个是 div 元素的子元素。您可以在 select 或:

中指定

cy.get('div button')

或者如果您需要更具体的内容,您也可以添加 class 个名称:

cy.get('div.offset-sm-3 button')

它不需要是直接父级,您可以在树的更高层找到合适的唯一 属性 到 select。