ThisCalculator

Everyday

How to Test Logout Flows in Cypress

Updated · Standard formula, shown below

This guide walks through testing logout functionality in Cypress, covering both the happy path and edge cases like session expiry and multiple tabs. You’ll learn how to verify that the logout button works, that session data is cleared, and that protected routes are no longer accessible. No prior Cypress knowledge is assumed beyond basic setup.

What You’ll Need

  • A Cypress project set up (install with npm install cypress and run npx cypress open).
  • An app with a login page and a logout button (or a way to trigger logout).
  • Credentials for a test user (or a way to stub authentication).
  • Knowledge of your app’s session mechanism: cookie, localStorage, or token.

Step-by-Step

  1. Create a new test file – In your Cypress project, create a file like cypress/e2e/logout.spec.js. This keeps logout tests separate from other flows.
  2. Set up the test suite – Use describe('Logout', () => { ... }) and beforeEach(() => { ... }) to navigate to a page where the user is logged in. You can either log in via UI or use cy.session() to persist authentication across tests.
  3. Log in the user – If you’re not using cy.session(), perform a login in the beforeEach. For example:
    cy.visit('/login');
    cy.get('[data-test=email]').type('test@example.com');
    cy.get('[data-test=password]').type('password123');
    cy.get('[data-test=login-btn]').click();
    cy.url().should('include', '/dashboard');

    If you’re using cy.session(), define it once and reuse it.

  4. Find the logout button – Use a stable selector like data-test or aria-label. Avoid using CSS classes that might change. For example: cy.get('[data-test=logout]'). If the button is only visible after opening a menu, click the menu first.
  5. Click logout and verify URL change – After clicking, assert that the URL returns to the login page or home page. For example: cy.url().should('include', '/login'). This confirms the client-side redirect happened.
  6. Verify session data is cleared – Check that cookies, localStorage, and sessionStorage are empty or contain expected values. Use cy.clearCookies() and cy.clearLocalStorage() to simulate a fresh state, but also assert that the app actually cleared them. For example:
    cy.window().then((win) => {
      expect(win.localStorage.getItem('token')).to.be.null;
      expect(win.sessionStorage.length).to.eq(0);
    });
    cy.getCookies().should('be.empty');

    Adjust these checks based on your app’s storage mechanism.

  7. Test that protected routes are blocked – After logout, try to visit a protected page directly, e.g., cy.visit('/dashboard'). The app should redirect to login or show an error. Assert the URL or the presence of a login form.
  8. Test the back button behavior – After logout, use cy.go('back') to simulate the browser back button. The app should not show cached protected content. This often requires the app to check authentication on each route change.
  9. Test logout from multiple tabs (if applicable) – If your app uses token-based auth, simulate a second tab by opening a new page in the same context. Use cy.visit('/') in a second test or use cy.window() to open a new window. Verify that logging out in one tab invalidates the session in the other.
  10. Test session expiry – If your app has a session timeout, you can test that the logout flow works after expiry. This is tricky; you might need to manipulate the token’s expiry or use cy.clock() to fast-forward time. For example, if the session expires after 30 minutes, use cy.clock() to advance time and then attempt an action.
  11. Run the test – Execute the test with npx cypress run or in the Cypress Test Runner. Watch for failures and adjust selectors or assertions as needed.

Common Mistakes

  • Hard-coded waits – Using cy.wait(5000) instead of waiting for elements to appear. This makes tests flaky and slow.
  • Selectors that are too brittle – Using CSS classes or XPath that change frequently. Prefer data-test attributes.
  • Not clearing cookies/localStorage before each test – This can cause tests to run with a stale session. Use beforeEach to clear them or use cy.session().
  • Assuming the app uses cookies – Some apps use localStorage or in-memory tokens. Test accordingly.
  • Only testing the happy path – If you only test that the URL changes, you might miss that the session is still valid. Always verify that protected resources are inaccessible.
  • Ignoring the back button – Many apps fail to handle the back button after logout, leaving the user able to see cached pages. Test this explicitly.

Tips

  • Use cy.session() for faster tests – It caches the login state and avoids re-logging in for every test, speeding up your suite.
  • Create custom commands – Write a Cypress.Commands.add('logout', ...) to reuse the logout logic across tests.
  • Test both UI and API logout – If your app has a logout API endpoint, verify that it’s called and returns a success status. Use cy.intercept() to spy on the request.
  • Use cy.clock() for time-based tests – If your session expires after a certain time, use cy.clock() to advance time without waiting.
  • Keep tests independent – Each test should be able to run alone. Avoid relying on state from previous tests.
  • Run tests in CI – Add the logout tests to your CI pipeline to catch regressions early.

Troubleshooting

  • Logout button not found – If the selector fails, open the app in the Cypress Test Runner, inspect the element, and use a more robust selector like data-test or role.
  • URL doesn’t change after logout – The app might be using a client-side router that doesn’t update the URL, or the logout is asynchronous. Wait for a specific element that appears after logout, or use cy.location('pathname') to check the path.
  • Session data still present after logout – If cookies or localStorage aren’t cleared, the app’s logout function might be incomplete. Check the app’s code and ensure the test waits for the logout request to complete before asserting.
  • Back button shows protected content – The app likely needs to check authentication on every route change. You can work around this by clearing the cache or using cy.reload() after logout, but the real fix is in the app.
  • Test fails only in CI – This often indicates a timing issue. Use cy.intercept() to wait for network requests, and avoid fixed waits. Also, ensure that the test user credentials are valid in the CI environment.
  • Multiple tabs test is flaky – Opening a new window in Cypress can be tricky. Use cy.window() to get the window object and then use cy.visit() with a different context. Alternatively, use cy.origin() if you need to test cross-origin scenarios.

Frequently Asked Questions

1. Do I need to test logout on every page?

No, but you should test logout from a page that requires authentication, and then verify that the user cannot access any protected routes. Testing from a few representative pages is sufficient.

2. How do I test logout if my app uses a single-page application (SPA) with client-side routing?

Use cy.location('pathname') to check the URL path after clicking logout. Also verify that the user is redirected to the login page and that the session is cleared.

3. Can I test logout without actually logging in?

Yes, you can create a test that directly sets the session token in localStorage or cookies, then visits a protected page and attempts to log out. This is faster but less realistic.

4. How do I test that the logout API is called correctly?

Use cy.intercept('POST', '/api/logout').as('logout'), then click the logout button and wait for the request. Assert that the response status is 200 or 204.

5. What if my app uses HTTP-only cookies for authentication?

Cypress can handle HTTP-only cookies, but you cannot inspect them with cy.getCookie() because they are not accessible to JavaScript. Instead, verify that the cookie is removed by making a request to a protected API and expecting a 401.

6. How do I test session expiry without waiting?

Use cy.clock() to control the system time. For example, if the session expires after 30 minutes, set the clock and then try to access a protected resource. You may need to mock the token’s expiry as well.

Related

Method: the standard formula for this calculation, rounded as each result states. See how the calculators work or report an error.