我想出了一种在需要时快速切换环境的方法,希望对您有所帮助。
要使用它,请将这些行添加到您的cypress/plugins/index.js
module.exports = (on, config) => {
// `on` is used to hook into various events Cypress emits
// `config` is the resolved Cypress config
// quick env switch
if (config.env.target) {
const { baseUrl, ...currentEnv } = config.env[config.env.target];
config.baseUrl = baseUrl;
config.env = { ...config.env, ...currentEnv }
}
return config;
}
现在您需要像这样设置目标环境并配置环境:
在你的cypress.json:
...
"env": {
"target": "dev",
"dev": {
"baseUrl": "http://www.myappurl-dev.com",
"apiUrl": "http://www.myapiurl-dev.com",
"username": "admin_dev"
},
"test": {
"baseUrl": "http://www.myappurl-test.com",
"apiUrl": "http://www.myapiurl-test.com",
"username": "admin_test"
}
},
...
您还可以在 cypress.env.json 中设置一个环境,该环境应该在您的 .gitignore 中,这样它就不会被推送到您的远程仓库。
cypress.env.json:
{
"target": "local",
"local": {
"baseUrl": "http://localhost:4000",
"apiUrl": "http://localhost:22742",
"username": "admin_local"
}
最后,您只需将target 更改为cypress.json 或cypress.env.json 即可在您的环境之间快速切换。
请记住,cypress.env.json 中设置的任何值都会覆盖cypress.json 中设置的值。
然后在你的代码中,你会像这样使用它:
it('should redirect to release', () => {
cy.get('[data-testid="my-link"]').click();
cy.url().should('include', Cypress.config('baseUrl');
});
编辑 #1
如果您的环境配置已存在于某处:
看看如何从cypress/plugins/index.jshere 设置环境值。他们正在展示如何获取您的.env,但您也可以读取.config 文件。
编辑#2:
我能够使用fs 和xml-js 从cypress/plugins/index.js 读取我的root/src/web.config:
const convert = require('xml-js');
const fs = require('fs');
module.exports = (on, config) => {
const xmlAngularConfig = fs.readFileSync('../path/to/your/config/file', 'utf8');
const jsonAngularConfig = convert.xml2json(xmlAngularConfig, { compact: true, spaces: 4 });
// Then you can add any value of jsonAngularConfig to cypress config
config.baseUrl = jsonAngularConfig.url;
// Don't forget to return config
return config;
}