Cypress系列(19)- 可操作类型的命令 之 hash()、window() 、root()、document()

241 阅读1分钟

持续创作,加速成长!这是我参与「掘金日新计划 · 6 月更文挑战」的第19天,点击查看活动详情

hash作用  

  • 获取页面当前的 url 的哈希值
  • 等价于 cy.location('hash') 

 

语法格式

cy.hash()
cy.hash(options)

options: 只有 timeout 和 log,不再展开讲了

 

正确写法

cy.hash()

 

实际栗子

html 代码

    <ul id="users">
        <li>
            <a href="#/users/8fc45b67-d2e5-465a-b822-b281d9c8e4d1">Fred</a>
        </li>
    </ul>

 

测试文件代码

 

测试结果

 

总结

感觉这方法应该用的不多,如果是普通的链接,是不会返回哈希值的

 

window作用

获取当前页面的 window 对象

 

语法格式

cy.window()
cy.window(options)

options: 只有 timeout 和 log,不再展开讲了

 

正确写法

cy.window()

 

实际栗子

测试文件代码

 

测试结果

 

.window() 命令的产物

可以看到,window 对象包含了很多属性值

root作用

获取当根元素

 

语法格式

cy.root()
cy.root(options)

options: 只有 timeout 和 log,不再展开讲了

 

正确写法

// 根元素是<html>
cy.root()

// 根元素是<nav>
cy.get('nav').within(($nav) => {
  cy.root() 
})

 

实际栗子

html 代码

<form id="contact">
    <input type="text" name="email">
    <input type="text" name="password">
    <button type="submit">Send</button>
</form>

 

测试文件代码

这里调用了两次 root()

  1. 直接通过 cy调用
  2. 在 .within() 回调函数中获取根元素

 

测试结果

可以看到, cy.root()  返回的就是 html 元素

 

而这里返回的是 form 元素

document作用

获取当前页面的 window.document 

 

语法格式

cy.document()
cy.document(options)

options: 只有 timeout 和 log,不再展开讲了

 

正确写法

cy.document()

 

实际栗子

测试文件代码

 

测试结果

 

document() 命令的产物