Cypress 29 🌲 Cheatsheet
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 / flag | Purpose |
|---|---|
cypress run --spec "cypress/e2e/x.cy.ts" | One spec |
cypress run --browser chrome | Pick a browser |
cypress run --browser electron --headed | Visible browser |
cypress run --record --key <k> | Upload to Cypress Cloud |
cypress run --parallel --record | Parallel across machines |
cypress run --group smoke | Named group |
cypress run --ci-build-id <id> | Manual run grouping |
cypress run --reporter junit | Reporter override |
cypress run --config baseUrl=… | Config override |
cypress run --env api=https://… | Env override |
cypress run --tag staging | Cloud tag |
cypress run --quiet | Suppress the spec list |
cypress run --auto-cancel-after-failures 2 | Fail-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;
},
},
});
| Key | Default | Meaning |
|---|---|---|
baseUrl | — | Prefix for cy.visit / cy.request |
defaultCommandTimeout | 4000 | Per-command budget |
requestTimeout | 15000 | cy.request |
responseTimeout | 30000 | cy.wait for a response |
pageLoadTimeout | 60000 | cy.visit / cy.reload |
taskTimeout | 60000 | cy.task |
execTimeout | 60000 | cy.exec |
retries | 0 | { runMode, openMode } |
testIsolation | true | Reset per test |
video | true | Record run mode |
waitForAnimations | true | Waits for CSS animation |
animationDistanceThreshold | 5 | px of movement |
numTestsKeptInMemory | 50 | Snapshots retained |
watchForFileChanges | true | Rerun on save |
experimentalWebKitSupport | false | WebKit 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
| Query | Purpose |
|---|---|
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
| Command | Notes |
|---|---|
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);
| Assertion | Checks |
|---|---|
exist / not.exist | In the DOM |
be.visible / not.be.visible | Rendered |
have.text / contain.text | Exact / substring |
have.value | Input value |
have.length | Set size |
have.class / have.attr / have.css | Attributes |
be.checked / be.disabled / be.enabled | State |
be.focused | Focus |
be.selected | Option |
be.above / be.below / be.within | Geometry |
match | Regex on text |
be.oneOf | Enum 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');
| Helper | Purpose |
|---|---|
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 method | Effect |
|---|---|
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);
},
});
});
| Option | Effect |
|---|---|
| key (array) | Cache identity |
validate() | Force a re-setup when it fails |
cacheAcrossSpecs | Share 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');
| Command | Effort |
|---|---|
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
| Knob | Default | Applies to |
|---|---|---|
defaultCommandTimeout | 4000 | Every command |
requestTimeout | 15000 | cy.request |
responseTimeout | 30000 | cy.wait('@alias') |
pageLoadTimeout | 60000 | cy.visit, cy.reload |
taskTimeout | 60000 | cy.task |
execTimeout | 60000 | cy.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' });
}
});
| Property | Returns |
|---|---|
this.currentTest.title | Name |
this.currentTest.state | 'passed' / 'failed' / 'pending' |
this.currentTest.currentRetry() | 0 on the first attempt |
this.currentTest.retries() | Configured max |
Debugging
| Tool | Mode | Effect |
|---|---|---|
| Time Travel hover | open | DOM snapshot at that command |
| Time Travel click | open | Pin the snapshot |
.debug() | open | debugger with the subject |
.debug() | run | Acts as cy.pause() |
cy.pause() | open | Step mode |
debugger in .then() | open | DevTools with locals |
cy.task('log', …) | both | Node log, visible in CI |
DEBUG=cypress:* | run | Internals |
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
| Artifact | Default | Location |
|---|---|---|
| Video | On in run mode | cypress/videos |
| Screenshot | On failure | cypress/screenshots |
| Downloads | Off | cypress/downloads |
| Cloud run | Off | Cypress Cloud |
reporter: 'junit',
reporterOptions: { mochaFile: 'results/[hash].xml', toConsole: true },
| Reporter | Purpose |
|---|---|
spec | Console tree (default) |
json | Machine-readable |
junit | CI systems |
teamcity | TeamCity |
mochawesome | HTML 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');
});
| Framework | devServer |
|---|---|
| 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
| Symptom | Cause | Fix |
|---|---|---|
| Passes alone, fails in suite | Shared state | Keep testIsolation: true |
| Element covered | Overlay / animation | Assert on the overlay’s absence |
| Assertion never retries | .should() written as .then() | Restore .should() |
| Duplicate rows | beforeEach runs per attempt | Idempotent seed |
| Slow suite | cy.type default delay | { delay: 0 } |
| Login is slow | Full flow per test | cy.session() |
| Smooth-scroll race | scroll-behavior: smooth | Override to auto |
| Runner slows then crashes | Snapshots retained | numTestsKeptInMemory: 0 |
| Network race | No alias wait | cy.intercept().as() + cy.wait |
Cypress → Playwright quick map
| Cypress | Playwright |
|---|---|
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 / await | required |
The retry model shift:
| Concept | Cypress | Playwright |
|---|---|---|
| Query timing | once per chain | lazy, every action |
| Retry scope | chain ending in .should() | action + expect(locator) |
| Non-retrying | .then() | toBe, toEqual |
| Value across steps | .as('x') | local variable |
| Test body | synchronous | async + await |
| Isolation | testIsolation per test | fresh 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
| Package | Adds |
|---|---|
@testing-library/cypress | findByRole, findByLabelText, findByText |
cypress-real-events | realHover, realClick, drag |
cypress-axe | cy.checkA11y() |
@cypress/code-coverage | cy.task('coverage') |
cypress-mochawesome-reporter | HTML report |
cypress-grep | Tag-based filtering |
@cypress/webpack-dev-server | Component testing bundler |
cypress-wait-until | cy.waitUntil(fn) — usually a smell |
Common pitfalls
| Pitfall | Cause | Fix |
|---|---|---|
| Test “passes” but nothing ran | async / await in the body | Synchronous body |
undefined from a stored chainable | Chainable used as a value | .then() or .as() |
| Assertion never retries | .then() where .should() belongs | Restore .should() |
| Selector not found | Wrong attribute | data-cy or the TL plugin |
| Hover does nothing | cy.hover() is not built in | realHover or .trigger() |
| Drag does nothing | Not built in | cypress-real-events |
| Filesystem access fails | Test body is the browser | cy.task() |
| Second origin errors | No cy.origin() | Wrap the domain |
| Popup test impossible | Single-tab by design | Redesign the test |
cy.clock breaks timing | All 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 // ❌
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!