root
获取根DOM元素。
语法
cy.root()
cy.root(options)
用法
正确用法
cy.root() // 返回根元素 <html>
cy.get('nav').within(($nav) => {
cy.root() // 返回根元素 <nav>
})
参数
options (Object)
传入一个选项对象以更改.root()
的默认行为。
选项 | 默认值 | 描述 |
---|---|---|
log | true | 在命令日志中显示该命令 |
timeout | defaultCommandTimeout | 等待cy.root() 解析的超时时间,超过则超时 |
生成结果
cy.root()
返回根DOM元素。
默认情况下返回的根元素是<html>
。但是,当在.within()
命令中调用.root()
时,根元素将指向你当前"within"的元素。
cy.root()
是一个查询命令,可以安全地链式调用其他命令。
示例
HTML
获取根元素
cy.root() // 返回 <html>
Within
在.within()
回调函数中获取根元素
cy.get('form').within(($form) => {
cy.get('input[name="email"]').type('john.doe@email.com')
cy.get('input[name="password"]').type('password')
cy.root().submit() // 提交从'within'返回的表单
})
规则
要求
cy.root()
需要链式调用cy
。
断言
cy.root()
会自动重试,直到所有链式断言通过。
超时设置
cy.root()
可能会因等待添加的断言通过而超时。
命令日志
获取根元素
cy.root().should('match', 'html')
cy.get('.query-ul').within(() => {
cy.root().should('have.class', 'query-ul')
})
上述命令将在命令日志中显示为:

当点击命令日志中的root
命令时,控制台会输出以下内容:
