Cypress.config
在测试中_获取和设置_配置选项。
info
刚接触 Cypress?
caution
作用域
使用 Cypress.config
设置的配置_仅在当前测试文件中有效_。
Cypress 会隔离运行每个测试文件:浏览器会在不同测试文件之间退出。在一个测试文件中修改的配置不会在其他测试文件中生效。
caution
注意
并非所有配置值都能在运行时修改。详情请参阅下方的注意事项。
语法
Cypress.config()
Cypress.config(name)
Cypress.config(name, value)
Cypress.config(object)
参数
name (String)
要获取或设置的配置项名称。
value (Any)
要设置的配置项值。
object (Object)
通过对象字面量设置多个配置选项。
示例
无参数
从 Cypress 配置 中获取所有配置选项
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
module.exports = defineConfig({
defaultCommandTimeout: 10000,
})
import { defineConfig } from 'cypress'
export default defineConfig({
defaultCommandTimeout: 10000,
})
Cypress.config() // => {defaultCommandTimeout: 10000, pageLoadTimeout: 30000, ...}
名称
从 Cypress 配置 中返回单个配置选项
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
module.exports = defineConfig({
pageLoadTimeout: 60000,
})
import { defineConfig } from 'cypress'
export default defineConfig({
pageLoadTimeout: 60000,
})
Cypress.config('pageLoadTimeout') // => 60000
名称和值
在测试中修改 Cypress 配置 的配置项值
caution
作用域
请记住,使用此 API 对配置所做的任何更改将在_同一测试文件_的剩余测试中持续生效。
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
module.exports = defineConfig({
viewportWidth: 1280,
viewportHeight: 720,
})
import { defineConfig } from 'cypress'
export default defineConfig({
viewportWidth: 1280,
viewportHeight: 720,
})
Cypress.config('viewportWidth', 800)
Cypress.config('viewportWidth') // => 800
对象
通过传入对象覆盖 Cypress 配置 中的多个选项
- cypress.config.js 文件
- cypress.config.ts 文件
const { defineConfig } = require('cypress')
module.exports = defineConfig({
defaultCommandTimeout: 4000,
pageLoadTimeout: 30000,
})
import { defineConfig } from 'cypress'
export default defineConfig({
defaultCommandTimeout: 4000,
pageLoadTimeout: 30000,
})
Cypress.config({
defaultCommandTimeout: 10000,
viewportHeight: 900,
})
Cypress.config() // => {defaultCommandTimeout: 10000, viewportHeight: 900, ...}
注意事项
并非所有配置值都能随时修改
某些配置值是只读的,无法在测试运行时更改。任何不受 Cypress 直接控制的内容(如超时或环境变量)在运行时都会被忽略。请务必查看测试配置选项列表。
测试配置 vs Cypress.config()
要将特定的 Cypress 配置值 应用于测试套件或测试用例,可以向测试或套件函数传递测试配置对象。
虽然 Cypress.config()
会在整个测试文件中更改配置值,但使用测试配置只会更改测试套件或测试用例执行期间的配置值。在套件或测试完成后,这些值会重置为之前的默认值。
完整指南请参阅测试配置。
Cypress.config()
是同步执行的
需要注意的是,Cypress.config()
是同步执行的,不会等待其上方的 Cypress 命令执行完毕。如果需要在测试中途更新配置,请确保链式调用异步 Cypress 命令。
it('使用 cy.then', () => {
cy.visit('/my-test_page')
cy.click('#download-html').then(() => {
Cypress.config('baseUrl', null)
})
cy.visit('/downloads/contents.html')
})