Cypress系列(79)- getCookies() 命令详解

简介: Cypress系列(79)- getCookies() 命令详解

如果想从头学起Cypress,可以看下面的系列文章哦

https://www.cnblogs.com/poloyy/category/1768839.html

 

作用


获取所有 Cookie,返回一个 Cookie 对象数组

 

语法格式


cy.getCookies()

cy.getCookies(options)

 

options 参数

  • log:是否将命令显示到命令日志中,默认 true
  • timeout:命令超时时间

 

正确用法


cy.getCookies()

 

命令返回结果


返回一个 Cookie 对象组成的数组,每个 Cookie 对象都包含以下属性

  • domain
  • expiry (如果有)
  • httpOnly
  • name
  • path
  • sameSite (如果有)
  • secure
  • value

 

实际栗子


栗子一:直接访问网站

代码

image.png

可以用 .each() 来遍历 Cookie 对象数组

 

运行结果

image.png

getCookies 返回结果

image.png

Cookie 对象数组

 

栗子二:简单登录页面

代码

//<reference types="cypress" /R>
describe('getCookies 登录页面', function () {
    const username = 'jane.lane'
    const password = 'password123'
    before(function () {
        // 登录操作
        cy.visit("http://localhost:7079/login")
        cy.get("input[name=username]").type(username)
        cy.get("input[name=password]").type(password)
        cy.get("form").submit()
    })
    it('获取登录后的 cookie', function () {
        cy.getCookies()
            .should('exist')
            .should('have.length', 1)
            .each((cookie) => {
                // 循环遍历每个 Cookie 对象
                cy.log(cookie)
            })
            .then((cookies) => {
                // 打印 Cookie 对象数组
                cy.log(cookies)
            })
    })
})


运行结果

image.png


相关文章
|
JavaScript
Cypress系列(76)- cloest() 命令详解
Cypress系列(76)- cloest() 命令详解
278 0
Cypress系列(76)- cloest() 命令详解
|
索引
Cypress系列(74)- each() 命令详解
Cypress系列(74)- each() 命令详解
282 0
Cypress系列(74)- each() 命令详解
|
测试技术
Cypress系列(82)- clearCookies() 命令详解
Cypress系列(82)- clearCookies() 命令详解
134 0
Cypress系列(82)- clearCookies() 命令详解
|
测试技术
Cypress系列(81)- clearCookie() 命令详解
Cypress系列(81)- clearCookie() 命令详解
150 0
Cypress系列(81)- clearCookie() 命令详解
|
JSON 数据格式
Cypress系列(95)- writeFile() 命令详解
Cypress系列(95)- writeFile() 命令详解
208 0
Cypress系列(95)- writeFile() 命令详解
Cypress系列(80)- setCookie() 命令详解
Cypress系列(80)- setCookie() 命令详解
117 0
Cypress系列(80)- setCookie() 命令详解
Cypress系列(73)- within() 命令详解
Cypress系列(73)- within() 命令详解
239 0
Cypress系列(73)- within() 命令详解
Cypress系列(78)- getCookie() 命令详解
Cypress系列(78)- getCookie() 命令详解
261 0
Cypress系列(78)- getCookie() 命令详解
Cypress系列(46)- then() 命令详解
Cypress系列(46)- then() 命令详解
410 0
Cypress系列(46)- then() 命令详解
Cypress系列(48)- and() 命令详解
Cypress系列(48)- and() 命令详解
131 0