Cypress - 定位器
Cypress - 现代定位器和选择器策略
Section titled “Cypress - 现代定位器和选择器策略”Cypress 主要使用 CSS 选择器来识别网页上的元素,这种方式通常快速可靠。虽然 Cypress 可以通过 @cypress/xpath 等插件扩展支持 XPath,但 CSS 选择器是推荐的默认方式。现代最佳实践还强调使用 data-cy 或 data-testid 等测试专用属性,以获得更具弹性的选择器。
让我们通过一个 HTML 结构示例来探索常见的 CSS 选择器模式:
<html><body> <div id="main-content"> <h1 class="title primary-heading">Welcome</h1> <form data-cy="login-form"> <input type="email" name="email" placeholder="Enter your email" id="email-input" /> <input type="password" name="password" class="input-field password-field" /> <button type="submit" data-cy="submit-button">Login</button> </form> <div class="user-info"> <p>Not logged in</p> </div> </div></body></html>常见的 CSS 选择器策略
Section titled “常见的 CSS 选择器策略”- 按 ID:
cy.get('#email-input')(选择id="email-input"的元素)。标签名是可选的:input#email-input。 - 按 Class:
cy.get('.password-field')(选择class="password-field"的元素)。可以使用标签名:input.password-field。 - 按属性:
cy.get('[name="email"]')(选择name="email"的元素)。可以使用标签名:input[name='email']。 - 按测试专用属性(最佳实践):
cy.get('[data-cy="submit-button"]')(选择data-cy="submit-button"的元素)。强烈推荐使用这种方式,因为它将测试与 CSS 或 JS 更改解耦。 - 按标签名:
cy.get('button')(选择所有<button>元素。谨慎使用,尽量精确)。 - 父子遍历:
cy.get('form[data-cy="login-form"] input[name="email"]')(选择登录表单内的电子邮件输入框)。或者使用 Cypress 命令:cy.get('[data-cy="login-form"]').find('input[name="email"]')。 - 链式遍历:
cy.get('#main-content').children('.user-info').find('p')(在.user-info中查找段落,其中.user-info是#main-content的子元素)。
使用 cy.contains()
Section titled “使用 cy.contains()”cy.contains() 用于根据元素的文本内容选择元素。它可以接受一个可选的选择器作为第一个参数来缩小搜索范围。
// 查找包含 'Welcome' 的任何元素cy.contains('Welcome');
// 查找包含 'Login' 的按钮cy.contains('button', 'Login');
// 查找 data-cy='submit-button' 且包含 'Login' 的元素cy.contains('[data-cy="submit-button"]', 'Login');Selector Playground
Section titled “Selector Playground”Cypress 测试运行器包含一个 ‘Selector Playground’(选择器操场)功能。这个交互式工具可以帮助您通过在应用预览中点击元素来确定其唯一的选择器。它通常会提供带有合适选择器的最佳 cy.get() 命令。
如何使用它:
- 打开 Cypress 测试运行器。
- 运行一个测试或通过
cy.visit()打开您的应用。 - 点击测试运行器顶部的 ‘target’ 图标(打开 Selector Playground)。
- 在应用预览中将鼠标悬停在元素上并点击它们。
- Cypress 会在
cy.get()字段中提供一个建议的选择器。您可以直接将其复制到您的测试代码中。
虽然 Selector Playground 很有帮助,但务必审阅其建议,并考虑是否使用更健壮的选择器(如 data-cy 属性)对长期的测试稳定性更合适。
使用 XPath(如有必要)
Section titled “使用 XPath(如有必要)”如果 CSS 选择器不足以应对特定情况(例如,查找基于复杂关系或 cy.contains() 不易处理的文本内容的元素),您可以通过 @cypress/xpath 插件使用 XPath。
-
安装插件:
npm install -D @cypress/xpath或yarn add -D @cypress/xpath。 -
在您的
cypress/support/e2e.js文件(或如果您使用其他结构,则为cypress/support/commands.js文件)中添加require('@cypress/xpath')。
然后您就可以在测试中使用 cy.xpath('//your/xpath/expression') 了。
示例: cy.xpath('//button[contains(text(), "Submit")]')
延伸阅读: