You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Cypress测试中如何避免重复获取header元素以优化代码?

解决Cypress中复用header元素的问题

问题描述

编写暗黑模式测试用例时,频繁通过cy.get("header")获取元素,想将其复用但直接赋值给变量无效,希望简化测试代码。

原始测试代码

it("toggles darkmode", () => {
  //when
  cy.visit("localhost:3000");
  cy.get("header").contains("title", "moon-icon").click({ force: true });
  cy.get("header").should("contain", "sun-icon");
  cy.get("header").contains("title", "sun-icon").click({ force: true });
  cy.get("header").should("contain", "moon-icon");
});
it("remebers dark mode after refresh", () => {
  //when
  cy.visit("localhost:3000");
  cy.get("header").contains("title", "moon-icon").click({ force: true });
  cy.reload();
  //then
  cy.get("header").should("contain", "sun-icon");
});

解决方案

方法1:使用Cypress别名(.as())

这是Cypress官方推荐的复用元素方式,通过.as()给元素设置别名,后续用cy.get('@别名')调用:

it("toggles darkmode", () => {
  cy.visit("localhost:3000");
  cy.get("header").as("header"); // 给header设置别名

  cy.get("@header").contains("title", "moon-icon").click({ force: true });
  cy.get("@header").should("contain", "sun-icon");
  cy.get("@header").contains("title", "sun-icon").click({ force: true });
  cy.get("@header").should("contain", "moon-icon");
});
it("remebers dark mode after refresh", () => {
  cy.visit("localhost:3000");
  cy.get("header").as("header");

  cy.get("@header").contains("title", "moon-icon").click({ force: true });
  cy.reload();
  cy.get("@header").should("contain", "sun-icon");
});

方法2:自定义命令

在cypress/support/commands.js中添加全局可用的自定义命令:

// cypress/support/commands.js
Cypress.Commands.add("getHeader", () => cy.get("header"));

测试用例中直接调用该命令:

it("toggles darkmode", () => {
  cy.visit("localhost:3000");

  cy.getHeader().contains("title", "moon-icon").click({ force: true });
  cy.getHeader().should("contain", "sun-icon");
  cy.getHeader().contains("title", "sun-icon").click({ force: true });
  cy.getHeader().should("contain", "moon-icon");
});
it("remebers dark mode after refresh", () => {
  cy.visit("localhost:3000");

  cy.getHeader().contains("title", "moon-icon").click({ force: true });
  cy.reload();
  cy.getHeader().should("contain", "sun-icon");
});

方法3:函数封装

在测试文件中定义函数封装元素查询逻辑:

const getHeader = () => cy.get("header");

it("toggles darkmode", () => {
  cy.visit("localhost:3000");

  getHeader().contains("title", "moon-icon").click({ force: true });
  getHeader().should("contain", "sun-icon");
  getHeader().contains("title", "sun-icon").click({ force: true });
  getHeader().should("contain", "moon-icon");
});
it("remebers dark mode after refresh", () => {
  cy.visit("localhost:3000");

  getHeader().contains("title", "moon-icon").click({ force: true });
  cy.reload();
  getHeader().should("contain", "sun-icon");
});

注意:别名的作用域仅限当前测试用例(it块),如果需要跨用例复用,自定义命令或函数封装更合适。

内容的提问来源于stack exchange,提问作者user19786344

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.16 20:15:38