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

如何在Cypress测试启动时仅调用一次API获取全局常量?

Cypress全局获取测试常量的最优实现方案

你不想在每个测试文件重复编写获取常量的before()钩子,下面是几种高效的实现方式,按场景优先级排序:

方案一:全局支持文件的根级before()钩子(最常用)

Cypress的cypress/support/e2e.js(旧版本为cypress/support/index.js)是全局配置入口,这里定义的根级before()会在每个测试文件执行前自动运行,完全避免重复代码。

实现步骤:

  1. 在全局支持文件中编写获取逻辑,并将常量挂载到Cypress全局对象:
// cypress/support/e2e.js
before(() => {
  cy.request({
    url: "/constants/",
    method: "GET",
  }).then((response) => {
    expect(response.status).to.eq(200);
    // 用Cypress.env存储,全局可访问
    Cypress.env("TEST_CONSTANTS", response.body);
    // 也可以直接挂载到Cypress属性:Cypress.constants = response.body;
  });
});
  1. 任意测试文件中直接调用:
describe("My Tests", () => {
  it("My test", () => {
    const constants = Cypress.env("TEST_CONSTANTS");
    console.log(constants.SOME_VALUE);
    // 或直接使用 Cypress.constants.SOME_VALUE
  });
});

这个方案符合Cypress测试文件独立运行的隔离原则,确保每个测试文件都能拿到最新的常量。

方案二:整个测试套件仅获取一次常量(高效优化)

如果测试期间常量不会变动,可通过Node.js任务+缓存实现全局只请求一次API,减少重复请求开销。

实现步骤:

  1. 在cypress.config.js中定义Node端任务,用于获取常量(Node环境无法直接用cy.request,需用axios等HTTP库):
// cypress.config.js
const { defineConfig } = require("cypress");
const axios = require("axios");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      on("task", {
        async fetchTestConstants() {
          try {
            // 替换为你的实际API地址
            const response = await axios.get("http://your-test-domain/constants/");
            if (response.status !== 200) {
              throw new Error(`请求常量失败:${response.status}`);
            }
            return response.data;
          } catch (err) {
            console.error("获取常量出错:", err);
            throw err;
          }
        },
      });
    },
  },
});
  1. 在全局支持文件中缓存常量,避免重复请求:
// cypress/support/e2e.js
let cachedConstants;

before(() => {
  if (cachedConstants) {
    Cypress.env("TEST_CONSTANTS", cachedConstants);
    return;
  }
  cy.task("fetchTestConstants").then((constants) => {
    cachedConstants = constants;
    Cypress.env("TEST_CONSTANTS", constants);
  });
});
  1. 测试文件中使用方式和方案一完全一致。

方案三:自定义命令(灵活扩展)

如果需要更灵活的调用时机(比如某些测试按需获取),可以封装成自定义命令:

// cypress/support/e2e.js
Cypress.Commands.add("getConstants", () => {
  // 已缓存则直接返回
  if (Cypress.env("TEST_CONSTANTS")) {
    return cy.wrap(Cypress.env("TEST_CONSTANTS"));
  }
  // 未缓存则请求并存储
  return cy.request({
    url: "/constants/",
    method: "GET",
  }).then((response) => {
    expect(response.status).to.eq(200);
    Cypress.env("TEST_CONSTANTS", response.body);
    return response.body;
  });
});

// 可选:全局预加载,确保所有测试运行前已获取
before(() => {
  cy.getConstants();
});

测试文件中使用:

describe("My Tests", () => {
  it("My test", () => {
    cy.getConstants().then((constants) => {
      console.log(constants.SOME_VALUE);
    });
  });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 10:15:14