0
0
CypressHow-ToBeginner ยท 4 min read

How to Test Logout in Cypress: Simple Guide with Examples

To test logout in Cypress, simulate the user clicking the logout button or link, then assert that the user is redirected to the login page or that the session is cleared. Use cy.get() to find the logout element, cy.click() to trigger logout, and cy.url() or cy.contains() to verify successful logout.
๐Ÿ“

Syntax

Use cy.get() to select the logout button or link by a reliable selector like an ID or data attribute. Then use cy.click() to perform the logout action. Finally, use assertions like cy.url().should() to check the user is redirected or cy.contains() to confirm the login page is shown.

javascript
cy.get('[data-cy=logout-button]').click();
cy.url().should('include', '/login');
cy.contains('Login').should('be.visible');
๐Ÿ’ป

Example

This example shows a full Cypress test that logs in a user, clicks the logout button, and verifies the user is redirected to the login page.

javascript
describe('Logout Test', () => {
  it('logs out the user and redirects to login page', () => {
    // Visit the app and log in (assume login is successful)
    cy.visit('/');
    cy.get('[data-cy=username]').type('user1');
    cy.get('[data-cy=password]').type('password123');
    cy.get('[data-cy=login-button]').click();

    // Click the logout button
    cy.get('[data-cy=logout-button]').click();

    // Assert the URL includes /login
    cy.url().should('include', '/login');

    // Assert the login page contains 'Login' text
    cy.contains('Login').should('be.visible');
  });
});
Output
Test passes if logout redirects to login page and login text is visible.
โš ๏ธ

Common Pitfalls

  • Using unstable selectors like classes that change often instead of data attributes or IDs.
  • Not waiting for the logout action to complete before asserting the URL or page content.
  • Failing to clear session or cookies if logout requires it, causing false test passes.
javascript
/* Wrong: Using a generic class that might change */
cy.get('.btn').click();

/* Right: Use a stable data attribute selector */
cy.get('[data-cy=logout-button]').click();
๐Ÿ“Š

Quick Reference

Remember these key steps for logout testing in Cypress:

  • Use stable selectors like data-cy attributes.
  • Trigger logout with cy.click().
  • Assert redirection with cy.url().should().
  • Check page content with cy.contains().
  • Clear cookies or local storage if needed.
โœ…

Key Takeaways

Use stable selectors like data attributes to find the logout button reliably.
Trigger logout by clicking the logout element with cy.click().
Verify logout success by asserting URL change and visible login page elements.
Avoid flaky tests by waiting for logout completion before assertions.
Clear session data if your app requires it to fully log out the user.