Skip to content

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>
  • 按 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() 用于根据元素的文本内容选择元素。它可以接受一个可选的选择器作为第一个参数来缩小搜索范围。

// 查找包含 'Welcome' 的任何元素
cy.contains('Welcome');
// 查找包含 'Login' 的按钮
cy.contains('button', 'Login');
// 查找 data-cy='submit-button' 且包含 'Login' 的元素
cy.contains('[data-cy="submit-button"]', 'Login');

Cypress 测试运行器包含一个 ‘Selector Playground’(选择器操场)功能。这个交互式工具可以帮助您通过在应用预览中点击元素来确定其唯一的选择器。它通常会提供带有合适选择器的最佳 cy.get() 命令。

如何使用它:

  1. 打开 Cypress 测试运行器。
  2. 运行一个测试或通过 cy.visit() 打开您的应用。
  3. 点击测试运行器顶部的 ‘target’ 图标(打开 Selector Playground)。
  4. 在应用预览中将鼠标悬停在元素上并点击它们。
  5. Cypress 会在 cy.get() 字段中提供一个建议的选择器。您可以直接将其复制到您的测试代码中。

虽然 Selector Playground 很有帮助,但务必审阅其建议,并考虑是否使用更健壮的选择器(如 data-cy 属性)对长期的测试稳定性更合适。

如果 CSS 选择器不足以应对特定情况(例如,查找基于复杂关系或 cy.contains() 不易处理的文本内容的元素),您可以通过 @cypress/xpath 插件使用 XPath。

  1. 安装插件:npm install -D @cypress/xpath 或 yarn add -D @cypress/xpath。

  2. 在您的 cypress/support/e2e.js 文件(或如果您使用其他结构,则为 cypress/support/commands.js 文件)中添加 require('@cypress/xpath')。

然后您就可以在测试中使用 cy.xpath('//your/xpath/expression') 了。

示例: cy.xpath('//button[contains(text(), "Submit")]')

延伸阅读: