Cypress系列(78)- getCookie() 命令详解

简介: Cypress系列(78)- getCookie() 命令详解

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

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

 

作用


获取指定名称的 Cookie

 

语法格式


cy.getCookie(name)

cy.getCookie(name, options)

name 必传

 

options 参数

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

 

正确用法


// 获取 token 这个 Cookie

cy.getCookie('token')

 

命令返回结果


返回一个 Cookie 对象,并且包含以下属性

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

 

注意:当找不到指定 Cookie 时,该命令会返回 null

 

实际栗子


栗子一:直接访问网站

代码

image.png

  • 可以用 .should(exist) 判断 cookie 对象是否存在
  • 也可以用 .should('have.property') 判断这个 cookie 对象的某个属性是否包含指定的值
  • 最后用 .then() 暂存 cookie 对象,以便后续扩展使用

 

运行结果

image.png

getCookie 返回结果

image.png

一个 cookie 对象一定会包含上面的六个属性

 

栗子二:简单登录页面

代码

//<reference types="cypress" /R>
describe('getCookie 登录页面', 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.getCookie("cypress-session-cookie")
            .should('exist')
            .should('have.property', 'domain', "localhost")
            .then((cookies) => {
                cy.log(cookies)
            })
    })
})


运行结果

image.png

相关文章
Cypress系列(79)- getCookies() 命令详解
Cypress系列(79)- getCookies() 命令详解
191 0
Cypress系列(79)- getCookies() 命令详解
|
测试技术
Cypress系列(81)- clearCookie() 命令详解
Cypress系列(81)- clearCookie() 命令详解
147 0
Cypress系列(81)- clearCookie() 命令详解
Cypress系列(80)- setCookie() 命令详解
Cypress系列(80)- setCookie() 命令详解
114 0
Cypress系列(80)- setCookie() 命令详解
|
索引
Cypress系列(74)- each() 命令详解
Cypress系列(74)- each() 命令详解
281 0
Cypress系列(74)- each() 命令详解
Cypress系列(73)- within() 命令详解
Cypress系列(73)- within() 命令详解
234 0
Cypress系列(73)- within() 命令详解
|
测试技术
Cypress系列(82)- clearCookies() 命令详解
Cypress系列(82)- clearCookies() 命令详解
130 0
Cypress系列(82)- clearCookies() 命令详解
|
JSON 数据格式
Cypress系列(95)- writeFile() 命令详解
Cypress系列(95)- writeFile() 命令详解
206 0
Cypress系列(95)- writeFile() 命令详解
|
JavaScript
Cypress系列(76)- cloest() 命令详解
Cypress系列(76)- cloest() 命令详解
273 0
Cypress系列(76)- cloest() 命令详解
Cypress系列(48)- and() 命令详解
Cypress系列(48)- and() 命令详解
130 0
Cypress系列(46)- then() 命令详解
Cypress系列(46)- then() 命令详解
404 0
Cypress系列(46)- then() 命令详解