Cookies
Examples of managing cookies in Cypress, for a full reference of commands, go to docs.cypress.io
cy.getCookie()
To get a browser cookie, use the cy.getCookie()
command.
<div id="getCookie">
<button class="set-a-cookie btn btn-success">
Set Cookie
</button>
</div>
<script>
$('.set-a-cookie').on('click', function (e) {
e.preventDefault()
document.cookie = 'token=123ABC'
})
</script>
cy.clearCookies()
cy.get('#getCookie .set-a-cookie').click()
// cy.getCookie() yields a cookie object
cy.getCookie('token').should('have.property', 'value', '123ABC')
cy.getCookies()
To get all browser cookies, use the cy.getCookies()
command.
<div id="getCookies">
<button class="set-a-cookie btn btn-success">
Set Cookie
</button>
</div>
<script>
$('.set-a-cookie').on('click', function (e) {
e.preventDefault()
document.cookie = 'token=123ABC'
})
</script>
cy.clearCookies()
cy.getCookies().should('be.empty')
cy.get('#getCookies .set-a-cookie').click()
// cy.getCookies() yields an array of cookies
cy.getCookies()
.should('have.length', 1)
.its(0)
.should('include', {
name: 'token',
value: '123ABC',
httpOnly: false,
secure: false,
})
// there are also other properties in the cookie object
.and('include.keys', ['domain', 'path'])
cy.setCookie()
To set a browser cookie, use the cy.setCookie()
command.
cy.clearCookies()
cy.getCookies().should('be.empty')
cy.setCookie('foo', 'bar')
// cy.getCookie() yields a cookie object
cy.getCookie('foo').should('have.property', 'value', 'bar')
cy.clearCookie()
To clear a browser cookie, use the cy.clearCookie()
command.
<div id="clearCookie">
<button class="set-a-cookie btn btn-success">
Set Cookie
</button>
</div>
<script>
$('.set-a-cookie').on('click', function (e) {
e.preventDefault()
document.cookie = 'token=123ABC'
})
</script>
cy.clearCookies()
cy.getCookie('token').should('be.null')
cy.get('#clearCookie .set-a-cookie').click()
cy.getCookie('token').should('have.property', 'value', '123ABC')
// cy.clearCookies() yields null
cy.clearCookie('token').should('be.null')
cy.getCookie('token').should('be.null')
cy.clearCookies()
To clear all browser cookies, use the cy.clearCookies()
command.
<div id="clearCookies">
<button class="set-a-cookie btn btn-success">
Set Cookie
</button>
</div>
<script>
$('.set-a-cookie').on('click', function (e) {
e.preventDefault()
document.cookie = 'token=123ABC'
})
</script>
cy.clearCookies()
cy.getCookies().should('be.empty')
cy.get('#clearCookies .set-a-cookie').click()
cy.getCookies().should('have.length', 1)
// cy.clearCookies() yields null
cy.clearCookies()
cy.getCookies().should('be.empty')