October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
authentication

How to Prevent Cypress Cucumber Tests from Signing Out on Dashboard Actions

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

If a Cypress test appears to sign out when you click a dashboard action, first find out when authentication disappears. A new test or Cucumber scenario starts with cleared browser state by default when Cypress test isolation is enabled; that is different from an action logging the user out during one test. Restore authentication deliberately with cy.session(), visit the dashboard after restoring it, and inspect the action’s network traffic if the session vanishes mid-test. Without your adapter, configuration, and failing request, there is no single confirmed cause.

First locate when the sign-out happens

Run the failing scenario by itself, then run it with the full suite. Note the precise point where the authenticated UI disappears: at the start of a new it test, at the start of a Cucumber scenario, immediately after cy.session(), or directly after a dashboard click or its network request. These timings point to different causes; a failure only in a sequence suggests state coupling or cleanup, not proof that the dashboard control logs out.

Cypress’s guidance is that tests should be independently runnable. Cucumber likewise advises that scenarios be independent of one another. Keep the failure isolated before changing settings, and record the URL, visible state, and requests around the point of failure. See Cypress test isolation and Cucumber state.

What Cypress resets between tests

With Cypress end-to-end test isolation enabled, Cypress resets the page to about:blank and clears cookies, localStorage, and sessionStorage before each test. A successful login in one test therefore does not mean that the next test inherits the same browser authentication state. Check the effective testIsolation setting and any suite-level override rather than assuming the default from another project applies.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

This reset is not a universal wipe of every browser storage mechanism. IndexedDB persists, and cy.session() does not capture or clear IndexedDB. If an application keeps authentication in an unusual store, inspect that implementation as well. The cited Cypress documentation pages do not establish one version-specific behavior for every project; confirm defaults and APIs against the Cypress version installed in your project.

Restore login state with cy.session()

For authentication stored in cookies or local/session storage, put the login setup in a session helper and call it from the relevant beforeEach or scenario setup. A session caches and restores those browser stores; it does not guarantee that the dashboard page is loaded afterward. With isolation enabled, call cy.visit() after cy.session().

// cypress/support/commands.js (or another support module)
Cypress.Commands.add('loginAs', (username, password) => {
  cy.session([username], () => {
    cy.visit('/login');
    cy.get('[name="username"]').type(username);
    cy.get('[name="password"]').type(password, { log: false });
    cy.get('button[type="submit"]').click();

    // Replace this with the application's actual success condition.
    cy.location('pathname').should('eq', '/dashboard');
    cy.get('[data-testid="account-menu"]').should('be.visible');
  }, {
    validate() {
      // Use an app-specific check that proves the cached login is still valid.
      cy.request('/api/me').its('status').should('eq', 200);
    }
  });
});

// cypress/e2e/dashboard.cy.js
beforeEach(() => {
  cy.loginAs(Cypress.env('username'), Cypress.env('password'));
  cy.visit('/dashboard');
});

test('dashboard action keeps the user authenticated', () => {
  cy.get('[data-testid="dashboard-action"]').click();
  cy.get('[data-testid="account-menu"]').should('be.visible');
});

The selectors, paths, and endpoint above are illustrative: replace them with your application’s real login fields and authenticated success condition. Do not cache a session merely because a submit click completed. Login can involve asynchronous requests and redirects, so wait for a retryable assertion that reflects the application’s successful authenticated state, such as the expected URL and authenticated UI. Cypress notes that cy.getCookie() does not retry; choose an assertion strategy appropriate to the signal you are checking.

Give each session an ID that distinguishes the user and any setup values that change the resulting authentication state. An overly broad ID can cause unrelated setups to restore the same cached browser state. The validate() callback checks a restored session; if it fails, Cypress reruns the session setup. Choose a validation check that is meaningful for your application, such as a request to an authenticated endpoint or a visible authenticated page element. Review Cypress cy.session() for the API and current behavior.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Choose the setup method that matches what you are testing

Approach Best fit Trade-off
cy.session() with UI login The login interface itself is part of the test’s scope. More setup work than direct API login; wait until login has truly completed before the session is cached.
cy.session() with API login The dashboard test needs an authenticated user, but the login UI is tested elsewhere or is not in scope. Exercises the API authentication path, not the login interface. API responses can also change the browser’s cookies.
Isolation on, cached login restored per test You want independently runnable tests without repeating the full login flow. Requires a well-scoped session ID, a success assertion, and useful validation.
Isolation disabled for a suite The suite intentionally models a continuous browser session. Introduces state leakage, order sensitivity, and tests that may pass only after earlier tests.
Clear cookies in a Cucumber Before hook Scenarios share a browser and must begin from a clean state. Hook ordering matters: cleanup must happen before the scenario establishes its required login.

The right choice depends on whether login itself is under test and how the application stores authentication. Prefer independent scenarios and deliberate setup over relying on a previous scenario’s browser state.

Check Cucumber hooks and browser lifecycle

Review the adapter’s Before and After hooks, shared browser lifecycle, and helpers that clear cookies or storage. Cucumber’s state guidance says, “Scenarios must be independent of one other so it is important that state is not shared between scenarios.” If a browser is shared, its guidance recommends deleting cookies in a Before hook. Make the order explicit: clean stale state first, then establish the login needed by the scenario.

For example, avoid a cleanup hook that runs after login setup or an authentication helper that is skipped because a scenario is assumed to inherit state. Cucumber’s isolated step-definition or World state does not itself demonstrate that the external browser cookie jar is isolated. The exact hook APIs and lifecycle depend on the Cypress-Cucumber adapter in use, which is not specified here.

Trace requests if a click signs out within one test

If the loss occurs during one test rather than at a test boundary, inspect the browser’s Cypress command log and network traffic around the action. Look for navigation to a sign-in route, an explicit logout request, a failed or expired token, and a response that clears or replaces the authentication cookie with Set-Cookie. Check whether the dashboard action is expected to invalidate the session or whether a request failure is causing the app to redirect.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Cypress API requests and browser UI commands share the browser cookie jar. Cypress documents that cy.request() obtains matching cookies from the browser and applies returned Set-Cookie values back to it. That behavior lets an API login establish browser state, but a logout or cookie-clearing response can also remove it. Compare request and response headers before and after the action rather than treating the visual redirect alone as proof of the root cause.

// Illustrative API session setup. Adapt route, payload, and validation to your app.
cy.session('dashboard-user', () => {
  cy.request('POST', '/auth/login', {
    username: Cypress.env('username'),
    password: Cypress.env('password')
  }).its('status').should('eq', 200);
}, {
  validate() {
    cy.request('/api/me').its('status').should('eq', 200);
  }
});

cy.visit('/dashboard');
cy.get('[data-testid="dashboard-action"]').click();

This pattern is illustrative, not a claim about your app’s endpoint, payload, cookie policy, or response status. Adapt the assertions to the real authentication contract. If the API login succeeds but the subsequent page is unauthenticated, examine whether it set the expected cookie or storage value and whether another request immediately replaced or cleared it.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

When disabling test isolation is appropriate

Cypress permits { testIsolation: false } at an end-to-end describe block level. It keeps the page and browser state across tests in that suite, which can be appropriate when the test design deliberately models a continuous session. Cypress’s isolation guidance also states, “Tests should always be able to be run independently from one another and still pass.” Disabling isolation trades that independence for persistence; it should not be a first-line fix for a login setup that can be made explicit.

describe('continuous dashboard workflow', { testIsolation: false }, () => {
  // Tests here deliberately share page/browser state.
});

If you use this option, verify both the intended ordering and what happens when a test fails or runs alone. Otherwise later tests can inherit stale data, and a suite can become order-dependent without making the underlying authentication behavior clearer. See Cypress test isolation for the documented configuration context.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Troubleshooting by symptom

  • Only the next test is signed out: check whether isolation is enabled; restore login in that test’s setup with a session helper, then visit its page.
  • The page is blank or at about:blank after restoring a session: call cy.visit() after cy.session() when test isolation is enabled. Session restoration is not a page visit.
  • It fails only in the full suite: inspect scenario ordering, suite-level isolation overrides, and Cucumber hooks that clean or reuse state. Run the scenario alone as a comparison.
  • The first run logs in but later runs do not: check whether the session is cached before login finishes, whether its ID collides with another setup, and whether validate() checks a real authenticated condition.
  • The dashboard redirects after a click: inspect the request triggered by the click and responses that may clear or replace auth cookies; also check for expiry, explicit logout, or an application-side authorization failure.
  • API login appears successful but the UI is unauthenticated: verify the endpoint’s actual response, the cookie or storage mechanism used by the app, and whether another response overwrites it. Cypress applies Set-Cookie values from cy.request() to the browser cookie jar.
  • A Cucumber hook seems to cause the logout: confirm cleanup runs before login setup for each scenario, and that a later hook does not clear the state.
  • Authentication depends on IndexedDB: Cypress test isolation and cy.session() do not clear or capture IndexedDB; account for that separate storage mechanism in the test design.

Or skip the browser setup

ScreenshotNeo is a website screenshot API, not a Cypress authentication fix. If your task is to capture a dashboard page rather than diagnose why a test loses its login, one GET request returns an image or PDF. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

ScreenshotNeo accepts cookie and consent banners before capture and removes more than 60 known consent platforms, newsletter popups, and chat widgets; those steps can be turned off. Bot checks/CAPTCHAs, blank pages, timeouts, failed loads, and cache hits cost nothing, and each response reports the page verdict and billing status in headers. Its MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

The Free plan includes 1,000 shots per month without a card; paid plans start at $5 for 3,000 shots. Learn about ScreenshotNeo or sign up for 1,000 free screenshots a month, with no card required.

Frequently Asked Questions

Does cy.session() reload the dashboard after restoring authentication?

No. Restore the session, then explicitly visit the page your test needs when test isolation is enabled.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Should I disable Cypress test isolation to keep a user logged in?

Only when the suite intentionally models a continuous browser session; otherwise restore authentication per test so tests remain independently runnable.

Can a cy.request() response sign my test out?

Yes. Cypress applies returned Set-Cookie values to the browser cookie jar, so inspect responses that clear or replace authentication cookies.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Read next

Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.