Cypress - Cookies
Cypress - Managing Cookies
Section titled “Cypress - Managing Cookies”Cypress provides robust mechanisms for managing cookies during your tests. By default, Cypress automatically clears all cookies before each test to ensure a clean state. However, there are scenarios where you need to persist cookies or interact with them directly.
Modern Session Management with cy.session()
Section titled “Modern Session Management with cy.session()”For persisting login states or any session-specific data (cookies, localStorage, sessionStorage) across multiple tests, the recommended approach is to use the cy.session() command. This command caches and restores the session details, preventing the need to re-authenticate or re-establish state repeatedly.
Syntax for cy.session()
Section titled “Syntax for cy.session()”cy.session(id, setupFunction, options?)- id: A unique identifier for the session. Can be a string or an array.
- setupFunction: A function that Cypress executes to create the session if it’s not already cached. This function should perform the steps to establish the session (e.g., log in, set cookies).
- options (optional): An object to configure session validation or other behaviors.
Once cy.session() successfully completes, cookies, localStorage, and sessionStorage are automatically saved and restored for subsequent tests using the same session id.
Basic Cookie Manipulation Commands
Section titled “Basic Cookie Manipulation Commands”Cypress offers several commands for direct cookie interaction within a single test:
- cy.getCookie(name): Retrieves a specific cookie by its name.
- cy.getCookies(): Retrieves all cookies for the current domain.
- cy.setCookie(name, value, options?): Sets a cookie with a given name and value. You can also pass options like
domain,path,secure,httpOnly,expiry. - cy.clearCookie(name): Clears a specific cookie by its name.
- cy.clearCookies(options?): Clears all cookies from the current domain and subdomain. Options can be used to specify a domain.
Note: Cypress.Cookies.preserveOnce() and Cypress.Cookies.defaults() are deprecated and have been replaced by cy.session() for managing session state across tests. Cypress.Cookies.debug() is also deprecated; use browser DevTools or cy.log(JSON.stringify(cookies)) for debugging.
Implementation Examples
Section titled “Implementation Examples”Example 1: Basic Cookie Operations
Section titled “Example 1: Basic Cookie Operations”describe('Cookie Management Test', () => { beforeEach(() => { // Visit a page where cookies can be set cy.visit('https://www.example.com'); });
it('should set, get, and clear a cookie', () => { // Set a cookie cy.setCookie('myCookie', 'myValue', { domain: 'www.example.com' });
// Get the cookie and assert its properties cy.getCookie('myCookie').should('have.property', 'value', 'myValue');
// Get all cookies and log them cy.getCookies().then((cookies) => { cy.log('All cookies:', JSON.stringify(cookies)); });
// Clear the specific cookie cy.clearCookie('myCookie');
// Verify the cookie is cleared cy.getCookie('myCookie').should('be.null');
// Set multiple cookies for clearing all cy.setCookie('tempCookie1', 'val1'); cy.setCookie('tempCookie2', 'val2');
// Clear all cookies cy.clearCookies();
// Verify all cookies are cleared cy.getCookies().should('be.empty'); });});Example 2: Using cy.session() to Persist Login
Section titled “Example 2: Using cy.session() to Persist Login”describe('User Session Management', () => { beforeEach(() => { // Use cy.session to ensure login happens only once cy.session('userSession', () => { // Steps to log in the user cy.visit('https://your-app.com/login'); cy.get('input[name="username"]').type('testUser'); cy.get('input[name="password"]').type('password123'); cy.get('button[type="submit"]').click(); // Ensure login is successful, e.g., by checking URL or an element cy.url().should('include', '/dashboard'); // Optionally, validate that cookies are set after login cy.getCookie('session_id').should('exist'); }); // After cy.session, cookies are restored. Visit the page you want to test. cy.visit('https://your-app.com/dashboard'); });
it('should access user-specific data on the dashboard', () => { // User is already logged in due to cy.session() cy.get('.user-profile').should('contain.text', 'testUser'); });
it('should navigate to another protected page', () => { // Session is still active cy.visit('https://your-app.com/settings'); cy.get('.settings-header').should('be.visible'); });});These examples demonstrate modern cookie handling in Cypress, focusing on test independence and efficient session management.