0
0
Cypresstesting~15 mins

Cookie management in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify cookie management on example.com
Preconditions (2)
Step 1: Open https://example.com in the browser
Step 2: Set a cookie named 'session_id' with value 'abc123'
Step 3: Verify the cookie 'session_id' exists with value 'abc123'
Step 4: Clear the cookie 'session_id'
Step 5: Verify the cookie 'session_id' no longer exists
✅ Expected Result: The cookie 'session_id' is set correctly, then removed successfully.
Automation Requirements - Cypress
Assertions Needed:
Verify cookie 'session_id' value is 'abc123'
Verify cookie 'session_id' is removed
Best Practices:
Use cy.setCookie and cy.getCookie for cookie operations
Use cy.clearCookie to remove specific cookies
Use explicit assertions with should()
Avoid hardcoded waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Cookie management test on example.com', () => {
  beforeEach(() => {
    cy.visit('https://example.com');
  });

  it('sets, verifies, and clears a cookie', () => {
    // Set cookie
    cy.setCookie('session_id', 'abc123');

    // Verify cookie is set with correct value
    cy.getCookie('session_id').should('have.property', 'value', 'abc123');

    // Clear the cookie
    cy.clearCookie('session_id');

    // Verify cookie is removed
    cy.getCookie('session_id').should('be.null');
  });
});

This test visits https://example.com before each test to ensure a fresh state.

It sets a cookie named session_id with value abc123 using cy.setCookie.

Then it verifies the cookie exists and has the correct value using cy.getCookie and should('have.property', 'value', 'abc123').

Next, it clears the cookie with cy.clearCookie.

Finally, it verifies the cookie no longer exists by asserting cy.getCookie('session_id').should('be.null').

This approach uses Cypress commands consistently and relies on Cypress automatic waiting, avoiding manual waits.

Common Mistakes - 3 Pitfalls
Using cy.wait() to wait for cookie to be set
Using document.cookie directly instead of Cypress commands
Not verifying cookie value after setting it
Bonus Challenge

Now add data-driven testing to set and verify cookies with 3 different session_id values.

Show Hint