0
0
Cypresstesting~5 mins

Cookie management in Cypress

Choose your learning style9 modes available
Introduction

Cookies help websites remember you. Managing cookies in tests makes sure your site works well with saved info.

When you want to check if a user stays logged in after refreshing the page.
When testing if preferences like language or theme are saved correctly.
When you need to clear cookies to test a fresh visit to the site.
When verifying that cookies are set with correct values after actions.
When simulating different users by changing cookie data.
Syntax
Cypress
cy.getCookie(name)
cy.setCookie(name, value, options)
cy.clearCookie(name)
cy.clearCookies()

cy.getCookie(name) reads a cookie by its name.

cy.setCookie(name, value, options) creates or updates a cookie.

Examples
Gets the cookie named 'session_id'.
Cypress
cy.getCookie('session_id')
Sets a cookie named 'theme' with value 'dark'.
Cypress
cy.setCookie('theme', 'dark')
Removes the cookie named 'session_id'.
Cypress
cy.clearCookie('session_id')
Removes all cookies for the current domain.
Cypress
cy.clearCookies()
Sample Program

This test visits a page, sets a cookie named 'user' with value 'tester', checks it, then clears it and confirms it is gone.

Cypress
describe('Cookie management test', () => {
  it('sets, gets, and clears a cookie', () => {
    cy.visit('https://example.cypress.io')

    // Set a cookie
    cy.setCookie('user', 'tester')

    // Check the cookie value
    cy.getCookie('user').should('have.property', 'value', 'tester')

    // Clear the cookie
    cy.clearCookie('user')

    // Verify cookie is removed
    cy.getCookie('user').should('not.exist')
  })
})
OutputSuccess
Important Notes

Always clear cookies between tests to avoid unexpected results.

Use cy.getCookie with assertions to confirm cookie values.

Cookies are domain-specific; make sure you visit the right page before managing cookies.

Summary

Cookies store small info to remember users or settings.

Cypress commands let you set, get, and clear cookies easily.

Testing cookies helps ensure your site behaves correctly for returning users.