Skip to main content

url

获取当前活动页面的 URL。

info

这是 cy.location('href') 的别名。

语法

cy.url()
cy.url(options)

用法

正确用法

cy.url() // 以字符串形式返回当前 URL

参数

options (对象)

传入一个选项对象以更改 cy.url() 的默认行为。

cy.url( options )

选项默认值描述
decodefalse解码 URL
logtrue命令日志中显示该命令
timeoutdefaultCommandTimeout超时前等待 cy.url() 解析的时间

生成结果 了解主题管理

  • cy.url() 以字符串形式返回当前 URL。
  • cy.url() 是一个查询命令,可以安全地链式调用其他命令。

示例

无参数

断言 URL 是 http://localhost:8000/users/1/edit

// 点击锚点会使浏览器跳转到链接
cy.get('#user-edit a').click()
cy.url().should('include', '/users/1/edit') // => true
cy.url().should('eq', 'http://localhost:8000/users/1/edit') // => true

decode 选项

当 URL 包含非 ASCII 字符时,使用 decode 选项。

// 好奇的话,"사랑" 在韩语中意为 "love"。
cy.url({ decode: true }).should('contain', '사랑')

说明

Href 简写

URL 是 cy.location('href') 的别名

cy.url() 在底层使用了 href

cy.url() // 这些返回相同的字符串
cy.location('href') // 这些返回相同的字符串

区别

URL 与 href

给定远程 URL http://localhost:8000/index.html,以下 3 个断言是相同的。

cy.location('href').should('include', '/index.html')

cy.location().its('href').should('include', '/index.html')

cy.url().should('include', '/index.html')

hreftoString 来自 window.location 规范。

但你可能想知道 URL 属性来自哪里。根据 window.location 规范,location 对象实际上并没有 URL 属性。

cy.url() 存在是因为它是大多数开发者自然认为会返回完整当前 URL 的方式。我们几乎从不将 URL 称为 href

硬编码与使用配置对象

与其在断言中硬编码 URL,我们建议你在 Cypress 配置 中定义 baseUrl。更多细节请参阅我们的最佳实践指南中的 设置全局 baseUrl

给定远程 URL http://localhost:8000/index.html 和 baseUrl http://localhost:8000,以下断言是相同的。

cy.url().should('eq', 'http://localhost:8000/index.html')
cy.url().should('eq', Cypress.config().baseUrl + '/index.html') // 如果端口更改,测试不会失败

断言 URL 包含 "#users/new"

cy.url().should('contain', '#users/new')

规则

要求 了解命令链

  • cy.url() 需要链式调用 cy

断言 了解断言

  • cy.url() 会自动 重试,直到所有链式断言通过。

超时设置 了解超时机制

  • cy.url() 可能会因等待添加的断言通过而超时。

命令日志

上述命令将在命令日志中显示为:

命令日志 url

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

控制台日志 url

历史

版本变更
8.4.0添加 decode 选项
< 0.3.3添加 cy.url() 命令

另请参阅