location
获取当前活动页面的全局 window.location
对象。
语法
cy.location()
cy.location(key)
cy.location(options)
cy.location(key, options)
用法
正确用法
cy.location() // 获取 location 对象
cy.location('host') // 获取 location 对象的 host
cy.location('port') // 获取 location 对象的 port
参数
key (String)
location 对象的一个键。返回该键对应的值而不是完整的 location 对象。
options (Object)
传入一个选项对象来改变 cy.location()
的默认行为。
选项 | 默认值 | 描述 |
---|---|---|
log | true | 在命令日志中显示该命令 |
timeout | defaultCommandTimeout | 在超时前等待 cy.location() 解析的时间 |
生成结果
cy.location()
是一个查询命令,可以安全地链式调用其他命令。
当不传入 key
参数时:
cy.location()
返回包含以下属性的 location 对象:
hash
host
hostname
href
origin
pathname
port
protocol
search
toString
当传入 key
参数时:
cy.location()
返回 location 对象对应属性的字符串值
示例
无参数
对每个 location 属性进行断言
cy.visit('http://localhost:8000/app/index.html?q=dan#/users/123/edit')
cy.location().should((loc) => {
expect(loc.hash).to.eq('#/users/123/edit')
expect(loc.host).to.eq('localhost:8000')
expect(loc.hostname).to.eq('localhost')
expect(loc.href).to.eq(
'http://localhost:8000/app/index.html?q=dan#/users/123/edit'
)
expect(loc.origin).to.eq('http://localhost:8000')
expect(loc.pathname).to.eq('/app/index.html')
expect(loc.port).to.eq('8000')
expect(loc.protocol).to.eq('http:')
expect(loc.search).to.eq('?q=dan')
expect(loc.toString()).to.eq(
'http://localhost:8000/app/index.html?q=brian#/users/123/edit'
)
})
检查 location 的查询参数和路径名
我们可以在 .should()
命令中获取 location 对象并直接操作它。
cy.get('#search').type('niklas{enter}')
cy.location().should((loc) => {
expect(loc.search).to.eq('?search=niklas')
expect(loc.pathname).to.eq('/users')
})
Key
断言重定向是否生效
仅获取 pathname
并添加断言。
cy.visit('http://localhost:3000/admin')
cy.location('pathname').should('eq', '/login')
注意事项
原生 Location
无需使用 window.location
Cypress 会自动规范化 cy.location()
命令,并去除 window.location
中的额外值和属性。此外,cy.location()
返回的对象字面量是一个基本对象,而不是特殊的 window.location
对象。
当改变真实 window.location
对象的属性时,会强制浏览器导航离开。在 Cypress 中,返回的是一个普通对象,改变其属性不会影响导航。
window.location
的控制台输出
cy.window().then((win) => {
console.log(win.location)
})

.location()
的控制台输出
cy.location().then((loc) => {
console.log(loc)
})

规则
要求
cy.location()
需要链式调用cy
。
断言
cy.location()
会自动 重试 直到所有链式断言通过
超时设置
cy.location()
可能会因等待添加的断言通过而超时。
命令日志
对 location 的 href 进行断言
cy.location().should((loc) => {
expect(loc.href).to.include('commands/querying')
})
以上命令会在命令日志中显示为:

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