Cypress Pocket Book

Cypress Pocket Book — Uplatz

50 deep-dive flashcards • Wide layout • Fewer scrolls • 20+ Interview Q&A • Readable code examples

Section 1 — Fundamentals

1) What is Cypress?

JavaScript end-to-end and component testing framework for the web. Runs in the browser with automatic waits, time-travel UI, and great DX for modern SPAs.

npm i -D cypress
npx cypress open   # interactive
npx cypress run    # headless CI

2) E2E vs Component Testing

E2E automates full browser journeys; Component tests mount UI components in isolation. Use both for confidence and fast feedback.

# In cypress.config.ts
e2e: { baseUrl: "http://localhost:3000" }
component: { devServer: { framework: "react" } }

3) Folder Structure

Tests live under cypress/e2e/ and cypress/fixtures/, with support files and plugins in cypress/support/.

cypress/
  e2e/login.cy.ts
  fixtures/user.json
  support/commands.ts

4) First Test

Visit, select, assert. Cypress auto-retries until assertions pass or timeout hits—avoid manual sleeps.

describe('Home', () => {
  it('shows header', () => {
    cy.visit('/');
    cy.contains('Welcome').should('be.visible');
  });
});

5) Best Selectors

Prefer stable data-cy (or data-testid) attributes over classes/IDs that change with styling.

<button data-cy="login-submit">Sign in</button>
cy.get('[data-cy=login-submit]').click()

6) Assertions

Use Chai/jQuery assertions; Cypress chains are retried. .should() re-queries; .then() yields a value.

cy.get('.toast').should('contain.text','Saved')

7) Commands & Yielding

Cypress commands are async and yield subjects to the next command. Don’t assign to variables—chain instead.

cy.get('input').type('hello').should('have.value','hello')

8) Timeouts & Waiting

Avoid cy.wait(1000). Prefer implicit waits via .should() or network waits via aliases.

cy.intercept('GET','/api/user').as('user');
cy.wait('@user').its('response.statusCode').should('eq',200)

9) Cross-Browser

Run in Chrome/Edge (Chromium) and Firefox. Validate critical flows in both; align CI matrix accordingly.

npx cypress run --browser chrome
npx cypress run --browser firefox

10) Q&A — “Cypress vs Selenium?”

Answer: Cypress runs inside the browser with automatic waits and a rich dev UI; Selenium/WebDriver controls browsers externally and supports more environments/languages.

Section 2 — Core APIs & Patterns

11) Visiting & Navigation

Set a baseUrl and use relative paths. Use cy.location() and cy.url() to assert navigation.

cy.visit('/dashboard')
cy.location('pathname').should('eq','/dashboard')

12) Forms

Type, select, check, and submit with assertions on disabled/enabled states.

cy.get('[data-cy=email]').type('a@b.co')
cy.get('[data-cy=agree]').check().should('be.checked')

13) Fixtures

Load JSON from cypress/fixtures for test data and network stubs.

cy.fixture('user.json').then(u => {
  cy.get('[data-cy=email]').type(u.email)
})

14) Custom Commands

Abstract repeated flows (e.g., login) into cypress/support/commands.ts.

// support/commands.ts
Cypress.Commands.add('login', (email, pass) => {
  cy.request('POST','/api/login',{ email, pass });
});
declare global { namespace Cypress { interface Chainable { login(email:string, pass:string): Chainable<void> }}}

15) Network Control: cy.intercept()

Spy or stub requests/responses; alias and wait deterministically.

cy.intercept('GET','/api/todos', { fixture:'todos.json' }).as('todos')
cy.visit('/todos')
cy.wait('@todos')

16) API Testing: cy.request()

Hit APIs directly without UI; assert status and body.

cy.request('POST','/api/items',{ name:'Book' })
  .its('status').should('eq',201)

17) State & Sessions

Use cy.session() to cache login across specs for speed; clear cookies/localStorage between tests for isolation.

cy.session([email,pass], () => cy.login(email,pass))

18) Clocks & Timers

Control time with cy.clock() and cy.tick() for deterministic tests.

cy.clock(Date.UTC(2025,0,1))
cy.tick(60000)

19) Files: Upload/Download

Upload via input elements; verify downloaded files exist and content matches.

cy.get('input[type=file]').selectFile('cypress/fixtures/pic.png')

20) Q&A — “When to stub vs hit real API?”

Answer: Stub for edge cases, speed, and determinism; hit real APIs for contract confidence and auth flows in a dedicated suite/environment.

Section 3 — Strategy, Structure, CI & Data

21) Test Pyramid

Heavier unit/component; fewer e2e happy paths; a handful of critical journeys. Keep e2e stable and fast.

Unit > Component > E2E (counts)

22) Spec Design

One feature per spec, independent setup, no hidden coupling. Name specs by feature to aid reporting.

checkout.cy.ts, profile.cy.ts

23) Env & Secrets

Use cypress.env.json or OS vars (CYPRESS_*). Never commit secrets; inject via CI.

CYPRESS_baseUrl=https://staging.example.com

24) Config (TypeScript)

Centralize retries, viewport, reporter, and baseUrl.

// cypress.config.ts
import { defineConfig } from 'cypress'
export default defineConfig({
  e2e: { baseUrl:'http://localhost:3000', retries:{ runMode:2, openMode:0 } },
  video:true, screenshotsFolder:'cypress/screenshots'
})

25) Data Seeding

Seed via backend APIs or DB tasks in setupNodeEvents. Clean between specs for isolation.

// cypress/plugins/index.ts (setupNodeEvents)
on('task',{ seedDB: () => doSeed() })

26) Test Users

Create dedicated accounts/tenants; avoid reusing prod users. Reset state via API for idempotent runs.

cy.request('POST','/test-utils/reset-user',{ id:'u1' })

27) CI Basics

Run headless in containers; cache npm; split specs across machines for speed.

npx cypress run --record=false --browser chrome

28) GitHub Actions Example

Minimal CI with install, build, start app, and run Cypress.

- uses: actions/checkout@v4
- uses: actions/setup-node@v4
- run: npm ci
- run: npm run build && npm start &
- run: npx wait-on http://localhost:3000
- run: npx cypress run

29) Parallelization

Split spec files across CI nodes; aggregate results in reports. Keep specs similar duration.

# Matrix split by spec pattern or glob shards

30) Q&A — “Flaky test sources?”

Answer: Brittle selectors, fixed waits, unhandled network races, shared state, and time-dependent code. Fix with stable selectors, intercepts, and isolation.

Section 4 — Components, Mocking, Accessibility & Advanced

31) Component Testing (React)

Mount components with test providers and assert render/interaction quickly.

import { mount } from 'cypress/react18'
import { Button } from './Button'
it('clicks', () => {
  mount(<Button>Save</Button>);
  cy.contains('Save').click()
})

32) Mocking Modules

For component tests, stub fetch/axios or inject providers with mock services.

cy.stub(window,'fetch').resolves(new Response('{"ok":true}'))

33) Accessibility (a11y)

Integrate axe to catch violations in CI and during development.

cy.injectAxe(); cy.checkA11y()

34) Visual Testing (Snapshot)

Compare DOM snapshots or integrate percy/visual-diff tools for pixel diffs.

cy.get('#card').should('matchSnapshot')

35) Network Error Paths

Stub 500/429/timeout to validate UX in failure modes and retries.

cy.intercept('GET','/api/items',{ statusCode:500 })

36) Auth Strategies

Prefer API login via cy.request() to set session cookies/localStorage, skipping slow UI steps.

cy.request('POST','/auth',{ u,p }).then(setSession)

37) Iframes & Windows

Access iframe body after load; stub window.open for external links.

cy.get('iframe').its('0.contentDocument.body').should('not.be.empty')

38) Drag & Drop

Simulate pointer events or use helper plugins; assert final DOM state, not event calls.

cy.get('#drag').trigger('mousedown')
cy.get('#drop').trigger('mousemove').trigger('mouseup')

39) Stubbing Dates/Randomness

Seed RNG and freeze time to avoid flake on timestamp/UUID displays.

cy.clock(1700000000000); cy.stub(Math,'random').returns(0.42)

40) Q&A — “Component vs E2E for bugs?”

Answer: Reproduce quickly in component tests for logic/UI bugs; keep an E2E to guard the user journey. Use both for coverage.

Section 5 — Performance, Reporting, Governance & Interview Q&A

41) Performance Tips

Reduce network chatter with stubs, cache seeds, run component tests locally, and shard specs in CI. Keep screenshots/videos only on failure.

videoUploadOnPasses: false

42) Retries & Test Isolation

Enable retries in runMode. Reset state in beforeEach; avoid shared globals.

retries: { runMode: 2, openMode: 0 }

43) Reporting

Use Mocha reporters, JUnit XML for CI, and HTML for devs. Publish artifacts from CI.

npx cypress run --reporter junit --reporter-options "mochaFile=results.xml"

44) Coverage

Instrument app with Istanbul; merge coverage from component + e2e.

import '@cypress/code-coverage/support'

45) Linting Tests

ESLint with Cypress plugin to catch anti-patterns (e.g., unawaited promises, forbidden sleeps).

extends: ['plugin:cypress/recommended']

46) Accessibility Gate in CI

Fail the build on critical a11y issues; tag violations by severity to triage.

cy.checkA11y(null, { includedImpacts: ['critical'] })

47) Security & PII

Don’t log secrets; mask tokens in screenshots; run tests in non-prod with scrubbed data.

CYPRESS_RECORD_KEY from CI, not repo

48) Production Checklist

  • Stable data-cy selectors
  • Intercepts for determinism
  • Retries + isolation configured
  • CI sharding + reports
  • Coverage + a11y gates
  • Test data seeding/reset APIs

49) Common Pitfalls

Fixed waits, brittle selectors, test coupling, hitting prod APIs, and global state leakage. Cure with intercepts, data-cy, and cleanup.

No: cy.wait(5000)
Yes: cy.wait('@alias')

50) Interview Q&A — 20 Practical Questions (Expanded)

1) Why Cypress? Fast feedback, auto-waits, rich dev tools, and straightforward JS API.

2) E2E vs component? E2E for journeys; component for fast, focused UI logic.

3) Flake reducers? Stable selectors, intercepts, clock control, retries.

4) API login? Use cy.request() to set session—skip UI login for speed.

5) When to stub? Deterministic tests, error paths, 3rd-party outages.

6) Network assertions? Alias requests with cy.intercept() and assert status/body.

7) a11y in CI? Integrate axe, fail on critical issues.

8) Parallel strategy? Shard by spec duration/feature; keep specs balanced.

9) Handling time? cy.clock() + cy.tick() for timers and date UIs.

10) Secrets? Env vars via CI; never commit creds.

11) Page objects? Prefer custom commands and helpers over heavy POMs.

12) Cross-browser? Run on Chromium and Firefox; prioritize critical paths.

13) Test data? Seed/reset via backend tasks; isolate per spec.

14) Coverage merge? Combine e2e + component; enforce thresholds.

15) Visual diffs? Add visual snapshot tool for UI regressions.

16) Iframes? Access document via its('0.contentDocument') and wrap body.

17) File upload? Use selectFile on input; assert server result.

18) Accessibility roles? Prefer role/name selectors with Testing Library.

19) Test speed? Stub heavy calls, avoid long journeys; more component tests.

20) Reporting? JUnit/HTML + CI artifacts; dashboard for flakes and duration trends.