如何通过CLI为不同环境配置SuperTest E2E动态测试URL?
实现NestJS E2E测试环境端点动态切换的方案
1. 用环境变量快速切换目标环境
这是最直接的方案,通过在启动命令中注入环境变量,让测试代码根据变量动态生成API地址。
首先修改package.json的scripts,添加不同环境的测试命令:
{ "scripts": { "test:e2e:local": "TEST_ENV=local jest --env=node --verbose", "test:e2e:staging": "TEST_ENV=staging jest --env=node --verbose", "test:e2e:prod": "TEST_ENV=prod jest --env=node --verbose" } }
如果是Windows系统,环境变量语法不同,建议安装cross-env包实现跨平台兼容,命令改成:
{ "scripts": { "test:e2e:local": "cross-env TEST_ENV=local jest --env=node --verbose", "test:e2e:staging": "cross-env TEST_ENV=staging jest --env=node --verbose", "test:e2e:prod": "cross-env TEST_ENV=prod jest --env=node --verbose" } }
然后在E2E测试文件中读取环境变量,生成对应base URL:
import request from 'supertest'; // 动态获取基准地址 const getBaseUrl = () => { switch (process.env.TEST_ENV) { case 'staging': return 'https://stg-xyz.com'; case 'prod': return 'https://prod-xyz.com'; default: return 'http://localhost:8112'; } }; describe('Health Check', () => { const baseUrl = getBaseUrl(); it('should return OK', async () => { const response = await request(baseUrl).get('/health'); expect(response.status).toBe(200); expect(response.text).toBe('OK'); }); });
2. 用Jest配置文件隔离环境配置
如果需要管理更多测试配置(比如超时时间、全局变量),可以为不同环境单独创建Jest配置文件。
创建jest-e2e.staging.js:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', verbose: true, globals: { BASE_URL: 'https://stg-xyz.com' } };
创建jest-e2e.prod.js:
module.exports = { preset: 'ts-jest', testEnvironment: 'node', verbose: true, globals: { BASE_URL: 'https://prod-xyz.com' } };
原有的本地测试配置保留在jest-e2e.js中,设置BASE_URL: 'http://localhost:8112'。
然后修改package.json的scripts:
{ "scripts": { "test:e2e:local": "jest --config jest-e2e.js", "test:e2e:staging": "jest --config jest-e2e.staging.js", "test:e2e:prod": "jest --config jest-e2e.prod.js" } }
测试文件中直接使用全局变量:
import request from 'supertest'; describe('Health Check', () => { it('should return OK', async () => { const response = await request(global.BASE_URL).get('/health'); expect(response.status).toBe(200); expect(response.text).toBe('OK'); }); });
3. 用配置文件统一管理环境参数
如果测试环境的配置项较多(比如API密钥、超时时间),可以创建单独的配置文件集中管理:
在项目根目录创建config/test-env.js:
module.exports = { local: { baseUrl: 'http://localhost:8112', timeout: 5000 }, staging: { baseUrl: 'https://stg-xyz.com', timeout: 10000 }, prod: { baseUrl: 'https://prod-xyz.com', timeout: 10000 } };
测试文件中加载对应配置:
import request from 'supertest'; const envConfigs = require('../config/test-env.js'); const currentEnv = process.env.TEST_ENV || 'local'; const { baseUrl, timeout } = envConfigs[currentEnv]; describe('Health Check', () => { it('should return OK', async () => { const response = await request(baseUrl) .get('/health') .timeout(timeout); expect(response.status).toBe(200); expect(response.text).toBe('OK'); }); });
注意事项
- 生产环境的E2E测试建议谨慎执行,避免对线上服务造成影响,可添加运行前确认逻辑或限制执行权限。
- 若使用monorepo,确保环境变量或配置文件的路径在各个子包中能正确访问,可通过
process.cwd()或根目录相对路径定位配置文件。
内容的提问来源于stack exchange,提问作者SMJ
相关产品推荐
相关产品推荐

