| | |

Cypress 29 🌲 Cheatsheet

⏱️ Estimated read: 13 min | |

A dense reference for Cypress commands, config, CLI, and testing patterns. Tables and snippets only.


Install & CLI

npm i -D cypress                       # install
npx cypress install                    # download the binary
npx cypress verify                     # check the install
npx cypress open                       # interactive runner
npx cypress run                        # headless CI run
npx cypress info                       # environment report
npx cypress version                    # version + binary
Command / flagPurpose
cypress run --spec "cypress/e2e/x.cy.ts"One spec
cypress run --browser chromePick a browser
cypress run --browser electron --headedVisible browser
cypress run --record --key <k>Upload to Cypress Cloud
cypress run --parallel --recordParallel across machines
cypress run --group smokeNamed group
cypress run --ci-build-id <id>Manual run grouping
cypress run --reporter junitReporter override
cypress run --config baseUrl=…Config override
cypress run --env api=https://…Env override
cypress run --tag stagingCloud tag
cypress run --quietSuppress the spec list
cypress run --auto-cancel-after-failures 2Fail-fast on Cloud

Config — cypress.config.ts

import { defineConfig } from 'cypress';

export default defineConfig({
  e2e: {
    baseUrl: 'http://localhost:3000',
    specPattern: 'cypress/e2e/**/*.cy.{ts,tsx}',
    supportFile: 'cypress/support/e2e.ts',
    fixturesFolder: 'cypress/fixtures',
    testIsolation: true,
    retries: { runMode: 2, openMode: 0 },
    video: true,
    screenshotOnRunFailure: true,
    viewportWidth: 1280,
    viewportHeight: 720,
    defaultCommandTimeout: 4000,
    requestTimeout: 15000,
    responseTimeout: 30000,
    pageLoadTimeout: 60000,
    setupNodeEvents(on, config) {
      on('task', {
        log(message: string) { console.log(message); return null; },
      });
      return config;
    },
  },
});
KeyDefaultMeaning
baseUrl—Prefix for cy.visit / cy.request
defaultCommandTimeout4000Per-command budget
requestTimeout15000cy.request
responseTimeout30000cy.wait for a response
pageLoadTimeout60000cy.visit / cy.reload
taskTimeout60000cy.task
execTimeout60000cy.exec
retries0{ runMode, openMode }
testIsolationtrueReset per test
videotrueRecord run mode
waitForAnimationstrueWaits for CSS animation
animationDistanceThreshold5px of movement
numTestsKeptInMemory50Snapshots retained
watchForFileChangestrueRerun on save
experimentalWebKitSupportfalseWebKit via Playwright

Selectors & queries

cy.get('[data-cy=save]')                    // attribute selector
cy.get('.card').eq(2)                       // nth
cy.contains('Order confirmed')              // text
cy.contains('tr', 'Alice')                  // element containing text
cy.findByRole('button', { name: 'Save' })   // @testing-library/cypress
cy.findByLabelText('Email')                 // plugin
cy.findByText('Save')                       // plugin
cy.findByTestId('cart')                     // plugin
QueryPurpose
cy.get(selector)CSS query, retries until found
cy.contains(text)Text query
cy.contains(sel, text)Element containing text
cy.find(selector)Descendant of subject
cy.closest(selector)Nearest ancestor
cy.parent() / .parents()Ancestors
cy.children()Direct children
cy.siblings()Siblings
cy.next() / .prev()Adjacent siblings
cy.first() / .last() / .eq(n)Index
cy.filter(sel)Narrow the set
cy.not(sel)Exclude
cy.within(fn)Scope all queries
cy.focused()Active element
cy.root()Top of scope
cy.shadow()Shadow root of subject

Open shadow roots are pierced by cy.get() automatically; cy.shadow() is the explicit step.


Actions

CommandNotes
cy.click()Accepts { force, multiple, position }
cy.dblclick()
cy.rightclick()
cy.type(text)delay: 10 ms per char
cy.type('{enter}')Special keys
cy.clear()Empties the input
cy.check() / cy.uncheck()
cy.select(value)Value, text, or index
cy.selectFile(path)
cy.trigger('mouseover')Synthetic event
cy.focus() / cy.blur()
cy.scrollTo(pos)'top', 'bottom', 'center'
cy.scrollTo(x, y)Coordinates
cy.scrollTo('li:last')Child element
cy.press('Tab')Browser-level key, Chromium only
cy.get('[data-cy=email]').type('a@b.c');
cy.get('[data-cy=note]').type(longNote, { delay: 0 });   // fast path
cy.get('[data-cy=country]').select('DE');
cy.get('[data-cy=terms]').check();
cy.get('[data-cy=bio]').type('Hello{enter}');
cy.get('[data-cy=pay]').click({ force: true });          // skip checks
cy.get('[data-cy=file]').selectFile('fixtures/a.pdf');
cy.get('[data-cy=feed]').scrollTo('bottom', { duration: 0 });

Hover and drag are not built in — cypress-real-events provides .realHover(), .realMouseDown(), and .drag().


Assertions

.should() retries the whole chain. .then() runs once.

cy.get('[data-cy=item]').should('have.length', 3);
cy.contains('Order confirmed').should('be.visible');
cy.get('[data-cy=email]').should('have.value', 'a@b.c');
cy.get('[data-cy=row]').should('have.class', 'active');
cy.get('[data-cy=link]').should('have.attr', 'href', '/docs');
cy.get('[data-cy=box]').should('have.css', 'color', 'rgb(255, 0, 0)');
cy.get('[data-cy=total]').invoke('text').should('eq', '10.00');
cy.get('[data-cy=n]').should(($el) => expect($el.text()).to.eq('3'));
cy.get('@req').its('response.statusCode').should('eq', 200);
AssertionChecks
exist / not.existIn the DOM
be.visible / not.be.visibleRendered
have.text / contain.textExact / substring
have.valueInput value
have.lengthSet size
have.class / have.attr / have.cssAttributes
be.checked / be.disabled / be.enabledState
be.focusedFocus
be.selectedOption
be.above / be.below / be.withinGeometry
matchRegex on text
be.oneOfEnum membership

.and() is .should() with chain reading. expect and assert are Chai, used inside .should(cb) or .then().


Aliases & the queue

// Enqueue — nothing runs yet
cy.get('[data-cy=save]').click();

// Read a value inside .then()
cy.get('[data-cy=total]').then(($el) => {
  expect($el.text().trim()).to.eq('10.00');
});

// Alias the subject for later use
cy.get('[data-cy=row]').as('firstRow');
cy.get('@firstRow').find('[data-cy=edit]').click();

// Alias a request
cy.intercept('GET', '/api/cart').as('cart');
cy.get('[data-cy=refresh]').click();
cy.wait('@cart');
HelperPurpose
cy.wrap(value)Push a value onto the queue
cy.then(fn)Run once with the subject
cy.invoke('text')Call a method on the subject
cy.its('0.contentDocument')Read a property
cy.spread(fn)Spread an array subject
cy.each(fn)Iterate a subject
.as('name')Store the subject
cy.get('@name')Retrieve it
cy.end()Break the chain

A chainable is a description, not a value. A const holding cy.get(...) holds a placeholder.


Network interception

// Stub a response
cy.intercept('GET', '/api/users', { fixture: 'users.json' }).as('users');
cy.intercept('POST', '/api/order', { statusCode: 201, body: { id: 1 } });

// Modify and continue
cy.intercept('GET', '/api/cart', (req) => {
  req.continue((res) => { res.body.patched = true; res.send(); });
});

// Observe only
cy.intercept('GET', '/api/**', (req) => { req.continue(); }).as('any');

// Delay — simulate a slow network
cy.intercept('GET', '/api/orders', (req) => {
  req.on('response', (res) => { res.setDelay(2000); });
});

// Assert on the request
cy.wait('@order').then(({ request, response }) => {
  expect(request.body.qty).to.eq(2);
  expect(response?.statusCode).to.eq(201);
});

// Match by predicate object
cy.intercept({ method: 'POST', url: '/api/**', headers: { auth: '*' } });
Route handler methodEffect
req.reply(…)Stub
req.continue(fn)Pass through
req.destroy()Abort
req.redirect(url)Redirect
req.alias = 'name'Alias inline
req.on('request', fn)Observe before
req.on('response', fn)Observe after

Requests, tasks, files

// HTTP from the test, no browser
cy.request('/api/orders').its('body').should('have.length', 3);
cy.request({ method: 'POST', url: '/api/order', body: { qty: 2 } });
cy.request({ url: '/api/me', failOnStatusCode: false });   // allow 4xx

// Node-side work via setupNodeEvents
cy.task('resetDatabase');
cy.task('log', 'checkpoint');

// Fixtures
cy.fixture('users.json').then((users) => cy.intercept('GET', '/api/users', users));

// Files
cy.readFile('cypress/fixtures/a.json').then((a) => { /* … */ });
cy.writeFile('cypress/tmp/out.txt', 'hello');

cy.request fails on non-2xx unless failOnStatusCode: false. It does not share cookies with the page by default.


Sessions

Cypress.Commands.add('login', (email: string, password: string) => {
  cy.session([email, password], () => {
    cy.visit('/login');
    cy.get('[data-cy=email]').type(email);
    cy.get('[data-cy=password]').type(password);
    cy.get('[data-cy=signin]').click();
    cy.url().should('include', '/dashboard');
  }, {
    cacheAcrossSpecs: true,                 // reuse across spec files
    validate() {                            // runs on every restore
      cy.request({ url: '/api/me', failOnStatusCode: false })
        .its('status').should('eq', 200);
    },
  });
});
OptionEffect
key (array)Cache identity
validate()Force a re-setup when it fails
cacheAcrossSpecsShare across spec files

cy.session() clears cookies and storage before the setup block runs and restores the cached state after — it does not navigate.


cy.origin

cy.origin('https://shop.example.com', () => {
  cy.visit('/checkout');
  cy.contains('button', 'Pay').click();
});

// Pass values in
cy.origin('https://shop.example.com', { args: { email: 'a@b.c' } },
  ({ email }) => { cy.get('[data-cy=email]').type(email); });

// Pass values out via an alias
cy.origin('https://shop.example.com', () => {
  cy.get('[data-cy=n]').invoke('text').as('remoteTotal');
});
cy.get('@remoteTotal').should('eq', '10.00');

The callback runs in the second origin’s frame and cannot close over outer variables.


Clock, spies, stubs

// Fake the clock — install before navigation
cy.clock(Date.UTC(2025, 0, 1));
cy.visit('/dashboard');
cy.tick(1000 * 60 * 120);                 // advance two hours

// Fake only Date; timers and rAF stay real
cy.clock(Date.UTC(2025, 0, 1), ['Date']);

// Spies on application methods
cy.window().its('console').then((c) => cy.spy(c, 'log').as('log'));
cy.get('[data-cy=go]').click();
cy.get('@log').should('have.been.calledWith', 'sent');

// Stubs
cy.stub(win.navigator.clipboard, 'writeText').resolves();
cy.get('[data-cy=copy]').click();
cy.get('@writeText').should('have.been.calledOnce');
CommandEffort
cy.clock(now?, fakes?)Fake Date / timers
cy.tick(ms)Advance time
cy.spy(obj, 'method')Wrap, record
cy.stub(obj, 'method')Replace
.as('alias')Retrieve for assertions

Cookies & storage

cy.getCookie('session_id');
cy.setCookie('flag', 'on');
cy.clearCookie('session_id');
cy.clearCookies();
cy.getCookies();
cy.clearAllLocalStorage();
cy.clearAllSessionStorage();
cy.clearAllCookies();

testIsolation: true clears cookies, localStorage, and sessionStorage, and navigates to about:blank between tests.


Timeouts

KnobDefaultApplies to
defaultCommandTimeout4000Every command
requestTimeout15000cy.request
responseTimeout30000cy.wait('@alias')
pageLoadTimeout60000cy.visit, cy.reload
taskTimeout60000cy.task
execTimeout60000cy.exec
cy.get('[data-cy=x]', { timeout: 10_000 }).should('be.visible');  // query
cy.contains('Done', { timeout: 20_000 });                        // text
cy.wait('@slow', { timeout: 30_000 });                           // alias
cy.task('seed', null, { timeout: 120_000 });                     // node

Retries & isolation

// cypress.config.ts
retries: { runMode: 2, openMode: 0 }

// Per test
it('authorizes a card', { retries: { runMode: 3 } }, () => { /* … */ });

// Per suite
describe('integrations', { retries: 3 }, () => { /* … */ });

// Opt out of isolation for one flow
it('step two', { testIsolation: false }, () => { /* … */ });
// Flake audit — beforeEach reruns on every attempt
afterEach(function () {
  if (this.currentTest.currentRetry() > 0) {
    cy.task('log', `FLAKY ${this.currentTest.title}`);
  }
  if (this.currentTest.state === 'failed') {
    cy.screenshot(this.currentTest.title, { capture: 'viewport' });
  }
});
PropertyReturns
this.currentTest.titleName
this.currentTest.state'passed' / 'failed' / 'pending'
this.currentTest.currentRetry()0 on the first attempt
this.currentTest.retries()Configured max

Debugging

ToolModeEffect
Time Travel hoveropenDOM snapshot at that command
Time Travel clickopenPin the snapshot
.debug()opendebugger with the subject
.debug()runActs as cy.pause()
cy.pause()openStep mode
debugger in .then()openDevTools with locals
cy.task('log', …)bothNode log, visible in CI
DEBUG=cypress:*runInternals
DEBUG=cypress:* npx cypress run
DEBUG=cypress:net-stubbing* npx cypress run
DEBUG=cypress:webpack* npx cypress run
DEBUG=cypress:server:util:process_profiler* npx cypress run
// Narrow exception filter — never a blanket return false
Cypress.on('uncaught:exception', (err) => {
  if (err.message.includes('ResizeObserver loop')) return false;
  return true;
});

// Console and page errors
cy.on('window:console', (msg) => cy.task('log', msg));
cy.on('fail', (err) => { cy.task('log', err.message); throw err; });

Artifacts & reporters

ArtifactDefaultLocation
VideoOn in run modecypress/videos
ScreenshotOn failurecypress/screenshots
DownloadsOffcypress/downloads
Cloud runOffCypress Cloud
reporter: 'junit',
reporterOptions: { mochaFile: 'results/[hash].xml', toConsole: true },
ReporterPurpose
specConsole tree (default)
jsonMachine-readable
junitCI systems
teamcityTeamCity
mochawesomeHTML report

Component testing

// cypress.config.ts
import { defineConfig } from 'cypress';

export default defineConfig({
  component: {
    devServer: { framework: 'react', bundler: 'vite' },
    specPattern: 'src/**/*.cy.tsx',
  },
});
// src/Button.cy.tsx
import { Button } from './Button';

it('fires onClick', () => {
  const onClick = cy.stub().as('onClick');
  cy.mount(<Button label="Save" onClick={onClick} />);
  cy.get('button').click();
  cy.get('@onClick').should('have.been.calledOnce');
});

it('renders a label', () => {
  cy.mount(<Button label="Save" />);
  cy.get('button').should('have.text', 'Save');
});
FrameworkdevServer
React{ framework: 'react', bundler: 'vite' }
Vue{ framework: 'vue', bundler: 'vite' }
Angular{ framework: 'angular', bundler: 'webpack' }
Svelte{ framework: 'svelte', bundler: 'vite' }

Custom commands & types

// cypress/support/commands.ts
Cypress.Commands.add('dataCy', (value: string) =>
  cy.get(`[data-cy=${value}]`)
);

Cypress.Commands.add('login', (email: string) => {
  cy.session(email, () => { cy.visit('/login'); /* … */ });
});

Cypress.Commands.overwrite('visit', (original, url, opts) => {
  return original(url, { ...opts, auth: { username: 'u', password: 'p' } });
});

// types
declare global {
  namespace Cypress {
    interface Chainable {
      dataCy(value: string): Chainable<JQuery<HTMLElement>>;
      login(email: string): Chainable<void>;
    }
  }
}
export {};

Combatting flake

SymptomCauseFix
Passes alone, fails in suiteShared stateKeep testIsolation: true
Element coveredOverlay / animationAssert on the overlay’s absence
Assertion never retries.should() written as .then()Restore .should()
Duplicate rowsbeforeEach runs per attemptIdempotent seed
Slow suitecy.type default delay{ delay: 0 }
Login is slowFull flow per testcy.session()
Smooth-scroll racescroll-behavior: smoothOverride to auto
Runner slows then crashesSnapshots retainednumTestsKeptInMemory: 0
Network raceNo alias waitcy.intercept().as() + cy.wait

Cypress → Playwright quick map

CypressPlaywright
cy.visit(url)page.goto(url)
cy.get('[data-cy=x]')page.getByTestId('x')
cy.contains('Save')page.getByText('Save')
cy.findByRole('button', { name })page.getByRole('button', { name })
.eq(n).nth(n)
.within(fn)assign the parent + chain
cy.intercept(…)page.route(…)
cy.wait('@alias')page.waitForResponse(…)
cy.fixture('x.json')import x from './x.json'
cy.task('x')ordinary Node function
cy.request(…)request.get(…)
cy.session(…)storageState + setup project
Cypress.Commands.add(…)test.extend({ … })
cy.clock() / cy.tick()page.clock.install() / .fastForward()
.its('0.contentDocument.body')frameLocator(…)
cy.origin(…)no boundary — plain goto
async / awaitrequired

The retry model shift:

ConceptCypressPlaywright
Query timingonce per chainlazy, every action
Retry scopechain ending in .should()action + expect(locator)
Non-retrying.then()toBe, toEqual
Value across steps.as('x')local variable
Test bodysynchronousasync + await
IsolationtestIsolation per testfresh context per test

Environment & CI

# env at run time
npx cypress run --env api=https://staging.example.com

# config at run time
npx cypress run --config baseUrl=https://staging.example.com,video=false

# CI detection — Cypress sets these automatically
CI=1
CYPRESS_CI_BUILD_ID=…
CYPRESS_RECORD_KEY=…
// read an env var in the test
Cypress.env('api');
Cypress.expose('featureFlag');            // public value, no secrets
# GitHub Actions
- uses: cypress-io/github-action@v6
  with:
    build: npm run build
    start: npm start
    wait-on: 'http://localhost:3000'
    record: true
    parallel: true
  env:
    CYPRESS_RECORD_KEY: ${{ secrets.CYPRESS_RECORD_KEY }}

Ecosystem worth knowing

PackageAdds
@testing-library/cypressfindByRole, findByLabelText, findByText
cypress-real-eventsrealHover, realClick, drag
cypress-axecy.checkA11y()
@cypress/code-coveragecy.task('coverage')
cypress-mochawesome-reporterHTML report
cypress-grepTag-based filtering
@cypress/webpack-dev-serverComponent testing bundler
cypress-wait-untilcy.waitUntil(fn) — usually a smell

Common pitfalls

PitfallCauseFix
Test “passes” but nothing ranasync / await in the bodySynchronous body
undefined from a stored chainableChainable used as a value.then() or .as()
Assertion never retries.then() where .should() belongsRestore .should()
Selector not foundWrong attributedata-cy or the TL plugin
Hover does nothingcy.hover() is not built inrealHover or .trigger()
Drag does nothingNot built incypress-real-events
Filesystem access failsTest body is the browsercy.task()
Second origin errorsNo cy.origin()Wrap the domain
Popup test impossibleSingle-tab by designRedesign the test
cy.clock breaks timingAll timers faked['Date'] only

The six rules to memorize

1. The test body is synchronous — no async, no await.

it('loads', () => { cy.visit('/cart'); });                 // ✅
it('loads', async () => { await cy.visit('/cart'); });     // ❌

2. A chainable is a description. Read it inside .then().

cy.get('[data-cy=n]').then(($el) => expect($el.text()).to.eq('3'));  // ✅
const $el = cy.get('[data-cy=n]'); expect($el.text()).to.eq('3');    // ❌

3. .should() retries. .then() does not.

cy.get('[data-cy=n]').should('have.text', '3');            // ✅
cy.get('[data-cy=n]').then(($e) => expect($e).to.have.text('3')); // ❌

4. Anything across commands is an alias.

cy.intercept('GET', '/api/x').as('x'); cy.wait('@x');      // ✅

5. Anything Node-side is a cy.task().

cy.task('resetDatabase');                                   // ✅

6. testIsolation: true stays on; slowness is fixed with cy.session().

cy.session(key, () => { /* login */ }, { cacheAcrossSpecs: true });  // ✅
testIsolation: false                                        // ❌

Was this helpful?


Stop using slow, ad-bloated tool sites! 🤮

🔎 Search “KandZ Tools” on Google to use many professional utilities for free.

KandZ.me is the ultimate minimalist hub for:
✅ Finance (Mortgage, Interest, Inflation)
✅ Tech (Base64, JSON, Dev Suite, IP)
✅ Health (BMI, BMR, TDEE)
✅ Productivity (Timer, Workspace, QR)

⚡️ Fast & Private
🔒 No data leaves your device
💎 100% Free

🔗 Use it now: https://tools.kandz.me
🔖 Bookmark it—you’ll need it later!