运行时动态指定环境变量
首先,在cypress.json中,更改如下:
{"viewportWidth": 1680,"viewportHeight": 1050,"env":{"test":{"CODEMAO_HOST": "https://test-xxxxx.cn","URL": "https://test-xxxxx.cn/","USERNAME": "xxxxxx","PASSWORD": "111111"},"staging": {"CODEMAO_HOST": "https://bxxxxx.cn","URL": "https://staging-xxxxxx.cn/","USERNAME": "xxxxx","PASSWORD": "111111"},"prod": {"CODEMAO_HOST": "https://xxxx.cn","URL": "https://xxxxx.cn/","USERNAME": "xxxxxx","PASSWORD": "111111"}}}
其次,更改”support/index.js”文件
///<reference types='cypress' />// Import commands.js using ES2015 syntax:import './commands'// Alternatively you can use CommonJS syntax:// require('./commands')// 根据最终的环境变量,重写urlbefore(()=>{const targetEnv = Cypress.env('testEnv')cy.log(`测试环境为: \n ${JSON.stringify(targetEnv)}`);cy.log(`环境详细配置为: \n ${JSON.stringify(Cypress.env(targetEnv))}`);cy.log(Cypress.env(Cypress.env('testEnv'))['CODEMAO_HOST']);Cypress.config('baseUrl', Cypress.env(targetEnv).Url);});
测试用例testLogin.js文件如下:
//testLogin.js///<reference types='cypress' />import LoginPage from '../../../page/login'describe('kitten登陆测试', function(){var username = Cypress.env(Cypress.env('testEnv'))['USERNAME'];const password = Cypress.env(Cypress.env('testEnv'))['PASSWORD'];before(function(){cy.loginRequest(username, password);});it('测试登陆成功', function(){const logininstance = new LoginPage()logininstance.isTargetPage();ecy.url().should('include', Cypress.env(Cypress.env("testEnv"))['URL'])});});
执行启动命令如下:
yarn cypress:open --env testEnv=prod
执行结果如下:
