its
获取先前生成主题的属性值。
info
如果想在先前生成的主题上调用函数
,请使用
.invoke()
。
语法
.its(propertyName)
.its(propertyName, options)
用法
正确用法
cy.wrap({ width: '50' }).its('width') // 获取 'width' 属性
cy.window().its('sessionStorage') // 获取 'sessionStorage' 属性
错误用法
cy.its('window') // 错误,不能从 'cy' 链式调用
cy.clearCookies().its('length') // 错误,'clearCookies' 不返回对象
参数
propertyName (String, Number)
要获取的属性索引、名称或嵌套属性名称(使用点表示法)。
options (Object)
传入选项对象以更改 .its()
的默认行为。
选项 | 默认值 | 描述 |
---|---|---|
log | true | 在命令日志中显示命令 |
timeout | defaultCommandTimeout | 等待 .its() 解析的超时时间,超过则超时 |
生成结果
.its()
返回属性的值。.its()
是一个查询,可以安全地链式调用其他命令。
示例
对象
获取属性
cy.wrap({ age: 52 }).its('age').should('eq', 52) // true
数组
获取索引
cy.wrap(['Wai Yan', 'Yu']).its(1).should('eq', 'Yu') // true
DOM 元素
获取 DOM 元素的 length
属性
cy.get('ul li') // 这会返回一个 jquery 对象
.its('length') // 调用 'length' 属性并返回值
.should('be.gt', 2) // 确保长度大于 2
请求
获取响应 body
中的 user
对象
cy
.request(...)
.its('body.user')
.then(user => ...)
或者使用解构
cy
.request(...)
.its('body')
.then(({user}) => ...)
字符串
获取标题的 length
cy.title().its('length').should('eq', 24)
函数
获取函数作为属性
const fn = () => {
return 42
}
cy.wrap({ getNum: fn }).its('getNum').should('be.a', 'function')
访问函数属性
可以访问函数以深入其自身属性,而不是调用它们。
// 应用代码
// 一个基本的工厂构造函数
const Factory = (arg) => {
// ...
}
Factory.create = (arg) => {
return new Factory(arg)
}
// 将其赋值给 window
window.Factory = Factory
cy.window() // 返回 window 对象
.its('Factory') // 返回 Factory 函数
.invoke('create', 'arg') // 现在调用其属性
使用 .its()
测试 window.fetch
嵌套属性
可以使用_点表示法_深入嵌套属性。
const user = {
contacts: {
work: {
name: 'Kamil',
},
},
}
cy.wrap(user).its('contacts.work.name').should('eq', 'Kamil') // true
存在性
等待 window
上的某个属性存在
cy.window()
.its('globalProp')
.then((globalProp) => {
// 现在 window.globalProp 存在,可以执行操作
})
断言 window
上不存在某个属性
cy.window().its('evilProp').should('not.exist')
规则
要求
.its()
需要从先前的命令链式调用。
断言
.its()
会自动重试,直到属性不是null
或undefined
。
超时设置
.its()
可能会因等待属性存在而超时。.its()
可能会因等待添加的断言通过而超时。
命令日志
获取别名路由的 responseBody
cy.intercept('/comments', { fixture: 'comments.json' }).as('getComments')
cy.get('#fetch-comments').click()
cy.wait('@getComments')
.its('response.body')
.should(
'deep.eq',
JSON.stringify([
{ id: 1, comment: 'hi' },
{ id: 2, comment: 'there' },
])
)
以上命令将在命令日志中显示为:

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

历史
版本 | 变更 |
---|---|
3.8.0 | 添加了对 options 参数的支持 |
3.7.0 | 添加了对 propertyName 参数类型为 Number 的支持 |