TypeScript实现:非Cypress环境下如何基于环境访问常量(类Cypress.env()功能)
无需Cypress或.env文件的TypeScript多环境配置方案
刚好碰到过类似的需求——不想依赖框架自带的环境配置,也不想用.env文件,直接把配置存在代码仓库里管理不同环境的参数。下面是一套TypeScript的实现方案,完全满足你的需求:
第一步:定义环境配置类型与数据
先通过TypeScript接口确保配置的类型安全,然后把各个环境的配置数据直接写在代码里:
// config.ts 文件 interface Environment { baseUrl: string; standardUserEmail: string; standardUserPassword: string; } type Environments = { development: Environment; production: Environment; }; // 维护所有环境的配置信息 const environments: Environments = { development: { baseUrl: 'https://dev-api.example.com', standardUserEmail: 'testing+standard@dev.example.com', standardUserPassword: 'dev-test-123', }, production: { baseUrl: 'https://api.example.com', standardUserEmail: 'standard-user@example.com', standardUserPassword: 'prod-secure-pass', }, };
第二步:编写环境选择逻辑
通过读取命令行的环境变量来自动切换配置,默认使用开发环境:
// 继续在 config.ts 中添加 const getEnvironmentData = (): Environment => { // 从环境变量获取当前环境,默认用development const currentEnv = process.env.ENVIRONMENT || 'development'; console.log(`当前使用环境:${currentEnv}`); // 类型断言确保环境名称合法 return environments[currentEnv as keyof Environments]; }; // 导出当前环境的配置对象 export = getEnvironmentData();
第三步:在测试代码中使用配置
直接引入配置文件,就能拿到对应环境的参数了,完全不需要修改测试逻辑:
// 测试文件示例 import 'mocha'; import { spec, request } from "pactum"; import { expect } from "chai"; import config from "../../config"; describe('API 认证测试', function () { const state = { token: "", }; before("获取认证Token", async () => { request.setBaseUrl(config.baseUrl); await spec().post('/auth') .withBody({ email: config.standardUserEmail, password: config.standardUserPassword }) .expectStatus(200) .expect((ctx) => { expect(ctx.res.body.token).to.be.a("string"); state.token = ctx.res.body.token; }); }); // 其他测试用例... });
如何切换环境运行测试
只需要在启动测试命令前加上环境变量即可:
# 运行生产环境测试 ENVIRONMENT=production npm test # 默认运行开发环境测试 npm test
这样既保持了配置的集中管理,又能灵活切换环境,完全不需要依赖Cypress或者.env文件。
内容的提问来源于stack exchange,提问作者George
相关产品推荐
相关产品推荐

