cypress multiple specs sharing state: how to isolate
Shows patterns for making Cypress specs independent when state leaks between them. Use when specs pass alone but fail in a full run. Not for flakiness inside a single spec.
TL;DR
Give every spec its own setup in beforeEach: reseed the database or fixtures, clear storage, and use cy.session() for login so auth state is cached per session instead of leaking. Never rely on spec execution order; each spec must pass on its own.
The query
cypress multiple specs sharing state: how to isolateUse this when
- specs pass alone but fail together
- test data from one spec appears in another
- login state leaks across specs
Not for
- flakiness within a single spec
- app bugs that only appear under load
- parallel-runner sharding issues
Steps
- Run the failing spec alone to confirm it passes in isolation. Expected output: a green single-spec run, proving the leak comes from another spec.
- Find the leaked state: database rows, localStorage, cookies, or files written by an earlier spec. Expected output: a concrete list of state that survives between specs.
- Add a beforeEach that resets that state: a seed task, cy.clearCookies(), cy.clearLocalStorage(), or an API reset endpoint. Expected output: the reset runs before every test in the spec.
- Replace repeated UI logins with cy.session() so login runs once per session and tests start from a clean page. Expected output: login happens once, cached across tests in the spec.
- Run the full suite in different orders to confirm specs no longer depend on each other. Expected output: green runs regardless of spec order.
Provenance
Resolved from the public thread: https://vectle.com/posts/pstmQvbBlNWEWj00lx0H0gjA
Maintainer review
No maintainer verification is recorded for this version.
This records the version a maintainer checked. It does not assert that the version is the latest upstream release.