Skip to main content
Cypress应用

配置API

Cypress允许您从配置中动态修改配置值和环境变量。

使用方法

caution

⚠️ 这段代码属于 setupNodeEvents 函数的一部分, 因此会在 Node 环境中执行。你不能在此函数中调用 Cypresscy 命令, 但可以直接访问文件系统和操作系统的其他部分。

要修改配置,您需要从导出的setupNodeEvents函数中返回一个配置对象。

const { defineConfig } = require('cypress')

module.exports = defineConfig({
// setupNodeEvents can be defined in either
// the e2e or component configuration
e2e: {
setupNodeEvents(on, config) {
console.log(config) // 查看所有配置内容!

// 修改配置值
config.defaultCommandTimeout = 10000
config.baseUrl = 'https://staging.acme.com'

// 修改环境变量值
config.env.ENVIRONMENT = 'staging'

// 重要:返回更新后的配置对象
return config
},
},
})

当您从setupNodeEvents函数返回一个对象时,Cypress会将其与原始配置进行"差异比较",并自动将解析后的值设置为您返回的内容。

如果不返回对象,则配置不会被修改。

caution

config对象还包含以下不属于标准配置的额外值。这些值是只读的,无法通过Cypress配置中的setupNodeEvents函数修改。

  • configFile: Cypress配置文件的绝对路径。有关此值的更多信息,请参阅--config-fileconfigFile文档。
  • projectRoot: 项目根目录的绝对路径(例如/Users/me/dev/my-project

解析后的值将显示在"Settings"选项卡中。

桌面应用中解析后的配置

Promise支持

此外,Cypress会尊重并等待您返回的Promise。这使您能够执行异步任务,并最终返回修改后的配置对象。完整示例请参阅在多个配置文件之间切换

示例

自定义可用浏览器

配置中包含系统上Cypress可用的浏览器列表。例如,您可以根据不同的测试目的更改或扩展该列表。

info

阅读我们关于启动浏览器的完整指南,了解更多信息。

在多个配置文件之间切换

这意味着您可以存储多个配置文件并按需切换,例如:

  • cypress.qa.json
  • cypress.dev.json
  • cypress.prod.json

如何组织配置和环境变量取决于您。

// 使用promisified的fs模块
const fs = require('fs-extra')
const path = require('path')

function getConfigurationByFile(file) {
const pathToConfigFile = path.resolve('..', 'config', `${file}.json`)

return fs.readJson(pathToConfigFile)
}

// 插件文件
module.exports = (on, config) => {
// 接受configFile值或默认使用development
const file = config.env.configFile || 'development'

return getConfigurationByFile(file)
}

您现在可以像这样切换配置和环境变量:

cypress run
cypress run --env configFile=qa
cypress run --env configFile=staging
cypress run --env configFile=production

每个环境会读取对应路径的配置文件:

cypress/config/development.json
cypress/config/qa.json
cypress/config/staging.json
cypress/config/production.json

这使您能够实现如下配置:

// cypress/config/development.json

{
"baseUrl": "http://localhost:1234",
"env": {
"something": "development"
}
}
// cypress/config/qa.json

{
"baseUrl": "https://qa.acme.com",
"env": {
"something": "qa"
}
}
// cypress/config/staging.json

{
"baseUrl": "https://staging.acme.com",
"env": {
"something": "staging"
}
}
// cypress/config/production.json

{
"baseUrl": "https://production.acme.com",
"env": {
"something": "production"
}
}

这是一个较简单的示例。请记住,您可以充分利用Node的全部功能。

如何编辑配置取决于您。您不必从文件系统读取——如果愿意,可以将所有配置存储在setupNodeEvents的内存中。

测试类型特定插件

您可以通过config.testingType属性访问正在运行的测试类型。测试类型为e2ecomponent,具体取决于在Cypress Launchpad中选择的是端到端测试还是组件测试。这允许您配置特定于测试类型的插件。

历史记录

版本变更
7.0.0config添加了testingType属性。