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

如何在Cypress 10x中通过cypress.config.js切换不同环境?

在Cypress 10+中加载不同环境的JSON配置文件

你可以直接在cypress.config.js(或.ts)中实现原有插件的逻辑,具体步骤如下:

1. 保留原有配置文件结构

继续保留config文件夹下的环境配置文件,内容无需修改:

local.env.json:

{
  "baseUrl": "localhost:8080"
}

uat.env.json:

{
  "baseUrl": "https://uat.test.com"
}

2. 修改cypress.config.js配置

在Cypress 10+中,使用defineConfig编写配置,直接在配置文件中读取环境变量并加载对应JSON配置:

const { defineConfig } = require("cypress");
const path = require("path");

module.exports = defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      // 获取环境变量中的version,默认值为'uat'
      const version = process.env.CYPRESS_VERSION || 'uat';
      // 加载对应的环境配置文件
      const envConfig = require(path.resolve(__dirname, `./config/${version}.env.json`));
      // 将配置合并到Cypress的env中
      config.env = { ...config.env, ...envConfig };
      return config;
    },
  },
});

如果使用TypeScript版本的cypress.config.ts,代码如下:

import { defineConfig } from "cypress";
import * as path from "path";

export default defineConfig({
  e2e: {
    setupNodeEvents(on, config) {
      const version = process.env.CYPRESS_VERSION || 'uat';
      const envConfig = require(path.resolve(__dirname, `./config/${version}.env.json`));
      config.env = { ...config.env, ...envConfig };
      return config;
    },
  },
});

3. 测试代码与CI命令保持不变

  • 测试中调用环境变量的方式无需修改:
    cy.visit(Cypress.env().baseUrl);
    // 或更简洁写法:cy.visit(Cypress.env('baseUrl'));
    
  • CI中传递参数的命令保持原有形式:
    CYPRESS_VERSION=uat npx cypress run
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 19:36:29