如何为Cucumber + Protractor E2E测试指定对应environment.json配置?
现有配置校验
tsconfig.e2e.json
当前配置无语法错误,仅需补充两项配置以支持直接导入JSON格式的环境文件:
在compilerOptions节点下新增:
"resolveJsonModule": true, "esModuleInterop": true
修改后的完整配置如下:
{ "extends": "../tsconfig.json", "compilerOptions": { "outDir": "../out-tsc/e2e", "baseUrl": "./", "module": "commonjs", "target": "es5", "resolveJsonModule": true, "esModuleInterop": true, "types": [ "chai", "cucumber", "node" ] } }
protractor.conf.js
当前基础配置无语法错误,缺少命令行参数解析和环境配置加载逻辑,需补充对应代码。
命令行指定环境配置实现方案
步骤1:整理环境配置文件
你可以选择将src/Environments下所有环境文件夹直接复制到e2e/config/environments目录下,保持目录结构不变:
e2e/ └── config/ └── environments/ ├── DEV/ │ └── environment.json ├── Test/ │ └── environment.json └── Production/ └── environment.json
也可以直接读取src目录下的原有文件,无需额外复制。
步骤2:修改protractor.conf.js
补充参数解析和环境加载逻辑,修改后完整配置如下:
// Protractor configuration file const path = require('path'); exports.config = { allScriptsTimeout: 11000, specs: [ './e2e/features/**/*.feature' ], capabilities: { 'browserName': 'chrome' }, directConnect: true, framework: 'custom', frameworkPath: require.resolve('protractor-cucumber-framework'), // 新增默认参数,默认使用DEV环境 params: { env: 'DEV' }, cucumberOpts: { require: ['./e2e/steps/**/*.ts'], tags: [], compiler: [] }, onPrepare() { require('ts-node').register({ project: 'e2e/tsconfig.e2e.json' }); // 加载对应环境的配置文件 const env = browser.params.env; // 如果直接读src下的文件,路径改为`../src/Environments/${env}/environment.json` const envConfigPath = path.resolve(__dirname, `./e2e/config/environments/${env}/environment.json`); const envConfig = require(envConfigPath); // 将环境配置挂载到browser.params,方便步骤定义中调用 browser.params.environment = envConfig; // 动态设置baseUrl exports.config.baseUrl = envConfig.ORIGIN; browser.baseUrl = envConfig.ORIGIN; } };
步骤3:配置运行命令
在package.json的scripts节点中新增对应环境的运行脚本:
{ "scripts": { "e2e:dev": "ng e2e --params.env=DEV", "e2e:test": "ng e2e --params.env=Test", "e2e:prod": "ng e2e --params.env=Production" } }
步骤4:在测试步骤中调用环境配置
在Cucumber的step定义文件中,直接通过browser.params.environment即可读取对应配置:
// 示例:获取当前环境的API地址 const apiOrigin = browser.params.environment.API_ORIGIN;
运行方式
- 执行对应环境的npm脚本即可:比如测试DEV环境运行
npm run e2e:dev - 也可以手动指定参数运行:
ng e2e --params.env=Test
内容的提问来源于stack exchange,提问作者Bmoe
相关产品推荐
相关产品推荐

