Cypress Interview Questions

Master your interview preparation with comprehensive Q&A covering all difficulty levels

How to Use This Interview Guide

Why Cypress Interviews Matter: Cypress is rapidly becoming the preferred E2E testing tool for modern web applications. Companies are actively hiring Cypress automation engineers, and interview questions focus on understanding how Cypress works internally, when to use it vs Selenium, and real-world testing scenarios.

What Interviewers Are Looking For:

  • Understanding of async/await patterns and how Cypress handles retries automatically
  • Knowledge of cy.intercept() for network stubbing — this is asked in almost every interview
  • Ability to explain why Cypress is better than Selenium for certain scenarios (not just memorized differences)
  • Real-world experience with flaky tests and how you've debugged them
  • Understanding of test isolation and state management between tests

How to Answer Interview Questions: Don't just recite textbook definitions. Explain the "why" behind the feature. For example, instead of "cy.intercept() stubs API calls," say "cy.intercept() lets us control API responses so we can test edge cases without hitting real servers, making tests faster and more reliable."

Common Interview Mistakes to Avoid:

  • ❌ Claiming Cypress can test multiple browsers (it can't — only Chrome, Firefox, Edge, Electron)
  • ❌ Saying cy.wait() is for timing (it's for network requests, not delays)
  • ❌ Not mentioning testIsolation and how it prevents test interdependencies
  • ❌ Forgetting about cy.session() for caching login state

Cypress Interview Questions - Beginner Level

Q 1

What is Cypress and what are its main advantages?

Answer: Cypress is a modern JavaScript-based end-to-end testing framework designed specifically for testing web applications. Unlike Selenium which runs outside the browser, Cypress runs inside the browser in the same JavaScript loop as your application, giving it unique advantages:

  • Automatic Retries: Cypress automatically retries commands and assertions until they pass or timeout. This eliminates 90% of flaky tests caused by timing issues.
  • Time-Travel Debugging: Step backward through your test execution to see what happened at each step. Invaluable for debugging failures.
  • Network Control: cy.intercept() lets you stub, spy on, or modify network requests without hitting real APIs.
  • Real-time Reload: Tests auto-rerun when you save changes, speeding up development cycle.
  • Developer Experience: Excellent documentation, active community, and intuitive API make Cypress much faster to learn than Selenium.

What Interviewers Want to Hear: Mention that Cypress runs inside the browser (not outside like Selenium), which gives it direct access to the DOM and JavaScript context. This is the key architectural difference that enables all its advantages.

Cypressarchitecturebrowser-basedadvantages
Q 2

How do you install Cypress in a project?

Use npm: `npm install --save-dev cypress`. Then open it with `npx cypress open` to launch the Cypress Test Runner in interactive mode.

`npminstall--save-devcypress`
Q 3

What is the difference between cy.visit() and cy.request()?

Answer:

cy.visit(): Navigates the browser to a URL and renders the entire page in the browser. Used when you need to test the UI and user interactions.

  • Loads all assets (HTML, CSS, JavaScript)
  • You can then interact with page elements using cy.get(), cy.click(), etc.
  • Example: cy.visit('/login')

cy.request(): Makes a direct HTTP request without loading the page in a browser. The response is returned directly for assertions.

  • No page render, no UI interaction possible
  • Useful for API testing, setup/teardown, or pre-populating data before UI testing
  • Example: cy.request('POST', '/api/login', { email, password })

Real-World Use Case: In a test, you might use cy.request() to log in via API (fast), then cy.visit('/dashboard') to test the dashboard UI. This is faster than logging in through the UI every time.

What Interviewers Want to Hear: Explain that cy.request() is particularly useful in beforeEach() hooks to set up test data without the UI overhead, making tests run faster.

visit()request()API testingsetup
Q 4

Explain the folder structure of a Cypress project.

Main folders: cypress/e2e (test files), cypress/support (reusable code/commands), cypress/fixtures (test data), cypress.config.js (configuration), and cypress/downloads and cypress/screenshots (artifacts).

Mainfolderscypress/e2e(test
Q 5

How do you select an element in Cypress?

Use cy.get() with CSS selectors: `cy.get('.button')`, ID selectors: `cy.get('#submit')`, attribute selectors: `cy.get('[data-test="login"]')`, or text content: `cy.contains('Click me')`.

get()selectorsget('button')`
Q 6

What is the purpose of cy.get() vs cy.contains()?

cy.get() selects elements by CSS selectors. cy.contains() selects elements by their visible text content. cy.contains() is useful when you don't have specific classes or IDs.

get()selectselementsselectors
Q 7

How do you perform a click action in Cypress?

Use cy.click(): `cy.get('button').click()`. You can also specify click position: `cy.get('button').click({position: 'topLeft'})` or multiple clicks: `cy.get('button').click({clickCount: 2})`.

click()get('button')click()`also
Q 8

Explain the concept of "assertions" in Cypress.

Assertions verify that the expected conditions are met. Examples: `cy.get('h1').should('be.visible')`, `cy.get('input').should('have.value', 'expected')`, `cy.url().should('include', '/home')`.

Assertionsverifyexpectedconditions
Q 9

What are the common assertion libraries used with Cypress?

Cypress supports Chai assertions by default (BDD and TDD syntax), jQuery assertions, and Sinon for spies/stubs. Example: `expect(value).to.equal(expected)`.

CypresssupportsChaiassertions
Q 10

How do you handle form input in Cypress?

Use cy.type() to input text: `cy.get('input[name="username"]').type('user123')`. For select dropdowns: `cy.get('select').select('option1')`. For checkboxes: `cy.get('input[type="checkbox"]').check()`.

type()inputtextget('input[name="use
Q 11

What is cy.intercept() and how is it used?

cy.intercept() allows you to intercept and manipulate HTTP requests and responses. Example: `cy.intercept('GET', '/api/users', {fixture: 'users.json'})` to mock an API response.

intercept()allowsinterceptmanipulate
Q 12

How do you wait for elements in Cypress?

Cypress automatically waits for elements. Use cy.get() which waits up to 4 seconds (default timeout). For explicit waits: `cy.wait(2000)` or `cy.get('element').should('be.visible')`.

Cypressautomaticallywaitselements
Q 13

What are fixtures in Cypress?

Fixtures are JSON files that contain test data. Located in cypress/fixtures directory. Load them with: `cy.fixture('users.json').then(data => { ... })` or use with cy.intercept() for mocking.

FixturesJSONfilescontain
Q 14

How do you navigate between pages in Cypress?

Use cy.visit() to go to a URL: `cy.visit('https://example.com')` or `cy.visit('/about')`. Use cy.go() for browser navigation: `cy.go('back')` or `cy.go('forward')`.

visit()visit('https//examplecom')`
Q 15

What is the purpose of cypress.config.js?

This configuration file allows you to set test options like baseUrl, timeout, viewportWidth, viewportHeight, number of test retries, recording settings, and custom environment variables.

configurationfileallowstest
Q 16

How do you run Cypress tests in headless mode?

Use command line: `npx cypress run`. This runs all tests without opening the Test Runner GUI. Optionally specify a spec file: `npx cypress run --spec "cypress/e2e/test.cy.js"`.

commandline`npxcypress
Q 17

What is the difference between beforeEach() and before() hooks?

before() runs once before all tests in a describe block. beforeEach() runs before each individual test. Use beforeEach() for test setup that needs to be repeated.

before()runsoncebefore
Q 18

How do you handle multiple elements with the same selector?

Use cy.get() to select all: `cy.get('.item')` returns all elements. Access specific ones: `cy.get('.item').eq(0)` (first), `cy.get('.item').last()` (last), or `cy.get('.item').each($el => { ... })`.

get()selectget('item')`
Q 19

What is the purpose of data-testid attributes?

data-testid attributes are added to HTML elements specifically for testing purposes. They provide stable selectors that won't break if styling classes change: `cy.get('[data-testid="submit-button"]')`.

data-testidattributesaddedHTML
Q 20

How do you take screenshots in Cypress?

Use cy.screenshot() to take a screenshot: `cy.screenshot()` (after each test). Or: `cy.screenshot('login-success')` to specify a custom name. Screenshots are saved in cypress/screenshots.

screenshot()takescreenshotscreenshot()`
Q 21

What are test retries in Cypress?

Test retries automatically re-run failed tests. Configure in cypress.config.js: `retries: { runMode: 2, openMode: 0 }`. Useful for handling flaky tests (not a fix, but a workaround).

Testretriesautomaticallyre-run
Q 22

How do you handle dropdown selections?

For select tags: `cy.get('select#country').select('USA')`. For custom dropdowns: `cy.get('.dropdown-trigger').click()` then `cy.get('.dropdown-option').contains('USA').click()`.

selecttagsget('select#country'select('USA')`
Q 23

What is cy.log() and when should you use it?

cy.log() prints messages to the Cypress command log for debugging: `cy.log('User logged in successfully')`. Useful for tracking test flow and debugging without console.log.

log()printsmessagesCypress
Q 24

How do you handle alerts in Cypress?

Use cy.on() to spy on alert events: `cy.on('window:alert', (str) => { expect(str).to.include('Delete?') })`. Cypress automatically dismisses alerts.

on()alerteventson('window
Q 25

What is viewport testing in Cypress?

Test how your application looks on different screen sizes. In cypress.config.js: `viewportWidth: 1280, viewportHeight: 720`. Or per-test: `cy.viewport(375, 667)` for mobile.

Testyourapplicationlooks
Q 26

How do you access element properties in Cypress?

Use .then() to access the element: `cy.get('input').then($input => { expect($input.val()).to.equal('text') })` or cy.invoke(): `cy.get('input').invoke('val').should('equal', 'text')`.

then()accesselementget('input')
Q 27

What is the purpose of cy.pause()?

cy.pause() pauses test execution at that point, allowing you to step through commands one by one in the Test Runner. Useful for debugging and understanding test flow.

pause()pausestestexecution
Q 28

How do you mock API responses in Cypress?

Use cy.intercept(): `cy.intercept('GET', '/api/users', {statusCode: 200, body: [{id: 1, name: 'John'}]})` to mock successful responses or errors.

intercept()intercept('GET''/api/users'{statusCode
Q 29

What are the benefits of using Cypress over Selenium?

Cypress runs in the same browser context as the app (no protocol overhead), has automatic waiting, better debugging (time-travel), cleaner syntax, better error messages, and focuses on modern web testing.

Cypressrunssamebrowser
Q 30

How do you handle file uploads in Cypress?

Use cy.get('input[type="file"]').selectFile('cypress/fixtures/document.pdf')` to upload a file. Alternatively, use cy.fixture() to get file content and pass it programmatically.

get('input[type="filselectFile('cypress/pdf')`upload
Q 31

What is the default timeout in Cypress and how do you change it?

Default timeout is 4000ms (4 seconds). Change globally in cypress.config.js: `defaultCommandTimeout: 10000`. Or per-command: `cy.get('element', {timeout: 8000})`.

Defaulttimeout4000msseconds)
Q 32

How do you check if an element is visible?

Use assertions: `cy.get('element').should('be.visible')` or `cy.get('element').should('not.be.visible')`. Also: `cy.get('element').should('have.css', 'display', 'block')`.

assertionsget('element')should('bevisible')`
Q 33

What is a stub in Cypress testing?

A stub is a fake implementation that replaces a real function. Used with cy.stub() or cy.window().then() to control function behavior: `cy.stub(obj, 'method').returns('mocked value')`.

stubfakeimplementationreplaces
Q 34

How do you verify URL changes in Cypress?

Use cy.url(): `cy.url().should('include', '/dashboard')` or `cy.url().should('eq', 'https://example.com/page')`. Also: `cy.location('pathname').should('eq', '/page')`.

url()url()should('include''/dashboard')`
Q 35

What are the common assertion patterns in Cypress?

Common patterns: `.should('be.visible')`, `.should('have.text', 'text')`, `.should('have.value', 'value')`, `.should('have.class', 'active')`, `.should('exist')`, `.should('have.length', 3)`.

Commonpatternsshould('bevisible')`
Q 36

How do you handle mouse events in Cypress?

Use cy.trigger() for any mouse event: `cy.get('element').trigger('mouseenter')`, `cy.get('element').trigger('mouseleave')`. Or use .hover(): `cy.get('element').trigger('mouseover')`.

trigger()mouseeventget('element')
Q 37

What is the purpose of cy.contains()?

cy.contains() finds and interacts with elements based on visible text: `cy.contains('Submit').click()` or `cy.contains('h1', 'Welcome').should('be.visible')`.

contains()findsinteractselements
Q 38

How do you handle keyboard events in Cypress?

Use cy.type() for text input: `cy.get('input').type('{enter}')` or `cy.get('input').type('{tab}')`. Or cy.trigger(): `cy.get('element').trigger('keydown', {keyCode: 27})`.

type()textinputget('input')
Q 39

What is the difference between .should() and .and()?

Both work identically for assertions. .should() starts a new assertion chain, while .and() chains additional assertions: `cy.get('input').should('be.visible').and('have.value', 'text')`.

Bothworkidenticallyassertions
Q 40

How do you verify page load time in Cypress?

Use cy.visit() with onBeforeLoad and onLoad callbacks to measure load time, or use cy.performance() (Cypress 13+). For basic checks: `cy.get('body').should('be.visible')`.

visit()onBeforeLoadonLoadcallbacks
Q 41

What is the purpose of cy.wrap()?

cy.wrap() wraps any value in a Cypress command chain, allowing you to use Cypress assertions and commands on non-DOM objects: `cy.wrap({name: 'John'}).should('have.property', 'name')`.

wrap()wrapsvalueCypress
Q 42

How do you handle multiple windows or tabs in Cypress?

Cypress doesn't support multi-tab testing. For links with target="_blank", use cy.invoke('removeAttr', 'target').click() to open in same tab, or cy.request() to test the URL directly.

Cypressdoesn'tsupportmulti-tab
Q 43

What is the difference between cy.get() and cy.find()?

cy.get() searches from the document root. cy.find() searches within a previously selected element (child selector): `cy.get('form').find('input')`.

get()searchesdocumentroot
Q 44

How do you skip or focus tests in Cypress?

Use it.skip() to skip a test: `it.skip('should test...', () => {})`. Use it.only() to run only that test: `it.only('should test...', () => {})`.

skip()skiptestskip('should
Q 45

What are implicit waits in Cypress?

Cypress automatically waits for elements to exist and be actionable. This implicit waiting is built into cy.get(), cy.click(), etc., making explicit waits rarely needed.

Cypressautomaticallywaitselements
Q 46

How do you handle date pickers in Cypress?

For input type="date": `cy.get('input[type="date"]').type('12122025')`. For calendar widgets: click the date picker and select the date, or use cy.invoke() to set value directly: `cy.get('input').invoke('val', '2025-12-12')`.

inputtype="date"get('input[type="dattype('12122025')`
Q 47

What is the purpose of environment variables in Cypress?

Environment variables store configuration values like API endpoints, credentials, or URLs. Define in cypress.config.js: `env: { apiUrl: 'https://api.example.com' }`. Access: `Cypress.env('apiUrl')`.

Environmentvariablesstoreconfiguration
Q 48

How do you validate text content in Cypress?

Use .should() with text assertions: `cy.get('h1').should('have.text', 'Welcome')`, `cy.get('p').should('contain.text', 'Hello')`, or regex: `cy.get('p').should('match', /pattern/)`.

should()textassertionsget('h1')
Q 49

What is the purpose of cy.readFile() and cy.writeFile()?

cy.readFile() reads files from the project: `cy.readFile('cypress/fixtures/data.json')`. cy.writeFile() writes files: `cy.writeFile('cypress/logs/test.log', 'log content')`.

readFile()readsfilesproject
Q 50

How do you organize tests in Cypress?

Use describe() blocks to group related tests, nested describe() for sub-groups, and meaningful test names with it(): `describe('Login', () => { it('should login with valid credentials', () => {}) })`.

describe()blocksgrouprelated

Cypress Interview Questions - Intermediate Level

Q 51

What is Page Object Model (POM) and how do you implement it in Cypress?

POM is a design pattern where each page is represented as a class with methods for interactions. Example: class LoginPage { login(user, pass) { cy.get('#user').type(user); cy.get('#pass').type(pass); } }.

designpatternwhereeach
Q 52

How do you create custom commands in Cypress?

Define in cypress/support/commands.js: `Cypress.Commands.add('login', (user, pass) => { cy.get('#user').type(user); cy.get('#pass').type(pass); cy.get('button').click(); })`. Use: `cy.login('user', 'pass')`.

Definecypress/support/comm`CypressCommands
Q 53

What is cy.session() and how is it used?

cy.session() caches browser state (cookies, localStorage) to speed up tests. Syntax: `cy.session('user-session', () => { cy.login(user, pass); })`. Reuses session across tests, avoiding repeated login.

session()cachesbrowserstate
Q 54

How do you handle network requests and responses in Cypress?

Use cy.intercept() to intercept requests: `cy.intercept('GET', '/api/users').as('getUsers')`. Then wait and assert: `cy.wait('@getUsers').its('response.statusCode').should('eq', 200)`.

intercept()interceptrequestsintercept('GET'
Q 55

What is the difference between cy.click({force: true}) and normal click?

Normal click checks if element is visible and actionable. {force: true} bypasses these checks and clicks regardless. Use force:true sparingly for hidden elements or overlays (not a best practice).

Normalclickcheckselement
Q 56

How do you handle shadow DOM in Cypress?

Cypress doesn't pierce shadow DOM by default. Use cy.get() with compound selectors or cy.shadow() plugin. Or use light DOM selectors: `cy.get('.shadow-host').shadow().find('.shadow-element')`.

Cypressdoesn'tpierceshadow
Q 57

What are data-driven tests and how do you implement them?

Data-driven tests run the same test with different data sets. Use cy.fixture() to load test data: `cy.fixture('users.json').forEach(user => { cy.login(user.email, user.password); })`.

Data-driventestssametest
Q 58

How do you handle API authentication in Cypress?

Use cy.request() with headers: `cy.request({ url: '/api/data', headers: { Authorization: 'Bearer token' } })`. Or use cy.intercept() to add auth headers: `cy.intercept(req => { req.headers['Authorization'] = 'Bearer token'; })`.

request()headersrequest({'/api/data'
Q 59

What is cy.invoke() and how is it different from cy.then()?

cy.invoke() calls a function on a subject: `cy.get('button').invoke('text').should('equal', 'Click')`. cy.then() accesses the subject but doesn't call functions: `cy.get('button').then($btn => { expect($btn.text()).to.equal('Click') })`.

invoke()callsfunctionsubject
Q 60

How do you test API endpoints directly in Cypress?

Use cy.request(): `cy.request('POST', '/api/users', {name: 'John'}).then(response => { expect(response.status).to.eq(201); expect(response.body).to.have.property('id'); })`.

request()request('POST''/api/users'{name
Q 61

What is the purpose of cy.within()?

cy.within() scopes queries within a specific element: `cy.get('form').within(() => { cy.get('input').type('text'); cy.get('button').click(); })`. Reduces selector complexity.

within()scopesquerieswithin
Q 62

How do you handle flaky tests in Cypress?

Identify root causes (network delays, timing issues, unstable selectors). Solutions: use explicit assertions instead of hard waits, improve selectors (use data-testid), mock APIs, use retries as a last resort.

Identifyrootcauses(network
Q 63

What is the purpose of cy.spy() and cy.stub()?

cy.spy() wraps a function to observe calls: `cy.spy(obj, 'method').should('have.been.calledWith', arg)`. cy.stub() replaces a function: `cy.stub(obj, 'method').returns('mocked')`.

spy()wrapsfunctionobserve
Q 64

How do you manage test data in Cypress?

Use fixtures for static data, database seeds for setup, API calls for creation, and cy.readFile()/cy.writeFile() for dynamic data. Clean up with afterEach() hooks to delete test data.

fixturesstaticdatadatabase
Q 65

What is continuous integration (CI) and how do you run Cypress in CI?

CI automates testing on every commit. Run Cypress in CI with: `npm run cypress:run`. Integrate with GitHub Actions, Jenkins, GitLab CI, etc. Configure in cypress.config.js for CI-specific settings.

automatestestingeverycommit
Q 66

How do you generate test reports in Cypress?

Use reporters like Mochawesome: `npm install --save-dev mochawesome` and configure in cypress.config.js: `reporter: 'mochawesome'`. Reports are generated in cypress/reports.

reporterslikeMochawesome`npm
Q 67

What is the purpose of cy.check() and cy.uncheck()?

cy.check() checks checkboxes: `cy.get('input[type="checkbox"]').check()`. cy.uncheck() unchecks them: `cy.get('input[type="checkbox"]').uncheck()`. Can check multiple: `cy.get('input[type="checkbox"]').check(['opt1', 'opt2'])`.

check()checkscheckboxesget('input[type="che
Q 68

How do you handle dropdown selections with custom elements?

Click the dropdown trigger, then click the option: `cy.get('.dropdown-trigger').click(); cy.get('.dropdown-menu').contains('Option').click();`. Or use cy.select() for native selects.

Clickdropdowntriggerthen
Q 69

What is the purpose of beforeEach() and afterEach() hooks?

beforeEach() runs before each test (setup), afterEach() runs after each test (cleanup). Use beforeEach() for login, navigation. Use afterEach() for logout, data deletion, cleanup.

beforeEach()runsbeforeeach
Q 70

How do you test form validation in Cypress?

Submit invalid data and verify error messages: `cy.get('input[name="email"]').type('invalid'); cy.get('button').click(); cy.get('.error').should('contain.text', 'Invalid email')`.

Submitinvaliddataverify
Q 71

What is the purpose of cy.request() vs cy.visit()?

cy.visit() loads the application in the browser. cy.request() makes HTTP requests directly (doesn't load UI). Use cy.request() for API testing, setup/teardown, or server-side validation.

visit()loadsapplicationbrowser
Q 72

How do you handle asynchronous operations in Cypress?

Cypress handles promises automatically. Use .then() or async/await with commands. Avoid manual Promise handling: instead of resolve/reject, use Cypress commands that return thenable values.

Cypresshandlespromisesautomatically
Q 73

What is the purpose of .scrollIntoView()?

Scrolls an element into view before interaction: `cy.get('#footer').scrollIntoView(); cy.get('#footer').should('be.visible')`. Useful for elements below the fold.

Scrollselementintoview
Q 74

How do you test pagination in Cypress?

Click next page and verify content changes: `cy.get('.next-button').click(); cy.get('tbody').should('contain', 'different data')`. Or cy.request() the next page endpoint directly.

Clicknextpageverify
Q 75

What is the purpose of cy.reload()?

cy.reload() reloads the page: `cy.reload()` or `cy.reload('forceReload')`. Useful for testing page refresh behavior or clearing client-side state.

reload()reloadspagereload()`
Q 76

How do you handle rate limiting and throttling in tests?

Use cy.intercept() to mock throttled responses. Or use DevTools Protocol (if supported) to simulate network conditions. Add delays with cy.wait(ms) for pacing.

intercept()mockthrottledresponses
Q 77

What is the difference between .first() and .eq(0)?

Both select the first element. .first() is more readable. Example: `cy.get('.item').first()` vs `cy.get('.item').eq(0)`. Both work the same.

Bothselectfirstelement
Q 78

How do you test redirect behavior in Cypress?

Verify URL after action: `cy.visit('/old-page'); cy.url().should('include', '/new-page')`. Or use cy.intercept() to spy on redirect requests.

Verifyafteractionvisit('/old-page')
Q 79

What is the purpose of cy.get().filter()?

Filter selects elements based on a condition: `cy.get('li').filter('.active').should('have.length', 1)`. Or filter by text: `cy.get('li').filter(':contains("Item 2")')`.

Filterselectselementsbased
Q 80

How do you handle iframes in Cypress?

Access iframe content: `cy.get('iframe').then($iframe => { const $body = $iframe.contents().find('body'); cy.wrap($body).find('button').click(); })`.

Accessiframecontentget('iframe')
Q 81

What is the purpose of .parents() and .closest()?

.parents() returns all parent elements. .closest() returns the first matching ancestor. Example: `cy.get('button').closest('.form').should('exist')`.

parents()returnsparentelements
Q 82

How do you test responsive design in Cypress?

Use cy.viewport() to test different screen sizes: `cy.viewport(375, 667)` for mobile. Test layout changes: `cy.get('.sidebar').should('not.be.visible')` on small screens.

viewport()testdifferentscreen
Q 83

What is the purpose of cy.get().type({delay: ms})?

Adds delay between keystrokes: `cy.get('input').type('hello', {delay: 100})`. Useful for testing real-time input handlers or autocomplete features.

Addsdelaybetweenkeystrokes
Q 84

How do you test localStorage in Cypress?

Access localStorage: `cy.window().then(win => { expect(win.localStorage.getItem('key')).to.equal('value'); })`. Or set: `cy.window().then(win => { win.localStorage.setItem('key', 'value'); })`.

AccesslocalStoragewindow()then(win
Q 85

What is the purpose of cy.request() method chaining?

cy.request() returns response for chaining: `cy.request('/api/users').then(resp => { cy.request('POST', '/api/users/' + resp.body[0].id + '/posts', {...}); })`.

request()returnsresponsechaining
Q 86

How do you debug Cypress tests?

Use cy.pause() to pause execution, cy.log() for logging, Cypress Test Runner's step-through debugging, or browser DevTools. Check command log for failures.

pause()pauseexecutionlog()
Q 87

What is the purpose of .should('exist') vs .should('be.visible')?

exist() checks if element is in DOM (may be hidden). be.visible() checks if element is visible (display, visibility, opacity). Use exist() for hidden elements, be.visible() for visible ones.

exist()checkselement(may
Q 88

How do you test long-running operations in Cypress?

Increase timeout: `cy.get('element', {timeout: 30000})`. Mock long operations with cy.intercept(). Or use cy.wait() but prefer assertion-based waiting.

Increasetimeoutget('element'{timeout
Q 89

What is the purpose of cy.its()?

cy.its() accesses a property of the previous subject: `cy.get('button').its('offsetHeight').should('be.greaterThan', 20)`. Useful for checking properties without .then().

its()accessespropertyprevious
Q 90

How do you handle browser back button in Cypress?

Use cy.go('back'): `cy.visit('/page1'); cy.visit('/page2'); cy.go('back'); cy.url().should('include', '/page1')`.

go('back')visit('/page1')visit('/page2')go('back')
Q 91

What is the purpose of .not() assertion?

.not() negates assertions: `cy.get('element').should('not.be.visible')`, `cy.get('input').should('not.have.value', 'old')`. Use for negative assertions.

not()negatesassertionsget('element')
Q 92

How do you test error handling in Cypress?

Mock error responses: `cy.intercept('GET', '/api/data', {statusCode: 500, body: {error: 'Server error'}})`. Then verify error UI: `cy.get('.error-message').should('contain', 'error')`.

Mockerrorresponsesintercept('GET'
Q 93

What is the purpose of .parent() vs .parents()?

.parent() returns the immediate parent. .parents() returns all ancestors. Use .parent() for direct parent, .parents() for searching up the tree.

parent()returnsimmediateparent
Q 94

How do you test dynamic content in Cypress?

Wait for elements: `cy.get('[data-loaded="true"]').should('exist')`. Or use cy.intercept() to spy on data loading requests and wait: `cy.wait('@dataLoad')`.

Waitelementsget('[data-loaded="tshould('exist')`
Q 95

What is the purpose of cy.then()?

cy.then() allows access to previous command results: `cy.get('button').then($btn => { const text = $btn.text(); cy.log(text); })`.

then()allowsaccessprevious
Q 96

How do you test URL query parameters?

Verify query params: `cy.url().should('include', '?search=test&page=1')`. Or use cy.location(): `cy.location('search').should('include', 'page=1')`.

Verifyqueryparamsurl()
Q 97

What is the purpose of .each() in Cypress?

.each() iterates over multiple elements: `cy.get('li').each(($item, index) => { cy.wrap($item).should('contain.text', 'Item ' + (index + 1)); })`.

each()iteratesovermultiple
Q 98

How do you handle cookies in Cypress?

Access cookies: `cy.getCookie('sessionId').should('exist')`. Set cookies: `cy.setCookie('sessionId', 'abc123')`. Clear: `cy.clearCookie('sessionId')`.

AccesscookiesgetCookie('sessionIdshould('exist')`
Q 99

What is the purpose of .and() in Cypress?

.and() chains additional assertions: `cy.get('input').should('be.visible').and('have.value', '')`. Functionally identical to should().

and()chainsadditionalassertions
Q 100

How do you test complex user workflows in Cypress?

Chain multiple commands in a describe block: `describe('Full workflow', () => { it('should complete flow', () => { cy.login(); cy.navigate(); cy.interact(); cy.verify(); }); })`.

Chainmultiplecommandsdescribe

Cypress Interview Questions - Advanced Level

Q 101

What is Cypress Component Testing and how is it used?

Component testing tests individual UI components in isolation. Mount components: `cy.mount(<MyComponent prop="value" />)`. Useful for testing React, Vue, Angular components without full app.

Componenttestingtestsindividual
Q 102

How do you implement the AAA pattern (Arrange-Act-Assert) in Cypress?

Arrange: setup test data and environment. Act: perform actions. Assert: verify results. Example: `it('test', () => { cy.visit('/'); cy.get('button').click(); cy.get('.result').should('exist'); })`.

Arrangesetuptestdata
Q 103

What is cy.task() and how is it used?

cy.task() runs Node.js code during tests. Define in cypress.config.js: `e2e: { setupNodeEvents(on, config) { on('task', { myTask: () => { return 'result'; } }); } }`. Call: `cy.task('myTask').then(result => {})`.

task()runsNodecode
Q 104

How do you test accessibility in Cypress?

Use cypress-axe plugin: `npm install --save-dev @axe-core/react`. Then: `cy.injectAxe(); cy.checkA11y();`. Scans for WCAG violations and accessibility issues.

cypress-axeplugin`npminstall
Q 105

What is the purpose of cy.performance() in Cypress?

cy.performance() (Cypress 13+) measures page performance metrics: `cy.performance().then(perf => { console.log(perf.timing); })`. Useful for performance testing.

performance()(Cypress13+)measures
Q 106

How do you implement a custom reporter in Cypress?

Create a reporter class extending Mocha reporter. Configure in cypress.config.js: `reporter: './custom-reporter.js'`. Implement onPending(), onPass(), onFail() methods.

Createreporterclassextending
Q 107

What is Allure reporting and how do you integrate it with Cypress?

Allure generates beautiful test reports. Install: `npm install --save-dev @shelex/cypress-allure-plugin`. Configure in cypress.config.js and generate reports: `allure generate`.

Alluregeneratesbeautifultest
Q 108

How do you handle TypeScript in Cypress?

Cypress supports TypeScript natively. Use .ts files for specs. Create cypress/support/types.ts for custom types. Configure tsconfig.json: `{ "compilerOptions": { "target": "es2020" } }`.

CypresssupportsTypeScriptnatively
Q 109

What is the purpose of Cypress Studio (experimental)?

Cypress Studio (experimental feature) generates test code visually by recording user interactions. Enable in cypress.config.js: `experimentalStudio: true`. Not recommended for production.

CypressStudio(experimentalfeature)
Q 110

How do you test WebSocket connections in Cypress?

Use cy.intercept() with WebSocket protocol (limited support). Or mock WebSocket: `cy.window().then(win => { win.WebSocket = class { send(msg) {} } })`.

intercept()WebSocketprotocol(limited
Q 111

What is the purpose of setupNodeEvents in cypress.config.js?

setupNodeEvents() allows custom Node.js code in the test runner process. Use for cy.task(), plugins, file manipulation, database operations: `e2e: { setupNodeEvents(on, config) { } }`.

setupNodeEvents()allowscustomNode
Q 112

How do you implement cross-browser testing in Cypress?

Cypress supports Chrome, Firefox, Edge via CLI: `npx cypress run --browser firefox`. Configure in CI to run multiple browsers. Use --browser option in cypress run.

CypresssupportsChromeFirefox
Q 113

What is the purpose of cy.origin() in Cypress?

cy.origin() tests multi-origin applications: `cy.origin('https://other-domain.com', () => { cy.get('button').click(); })`. Enables cross-domain testing.

origin()testsmulti-originapplications
Q 114

How do you handle visual regression testing in Cypress?

Use plugins like cypress-image-snapshot: `npm install --save-dev cypress-image-snapshot`. Call: `cy.screenshot(); cy.matchImageSnapshot();`. Compares visual diffs.

pluginslikecypress-image-snapsh`npm
Q 115

What is the purpose of .window() and .document() commands?

.window() accesses window object: `cy.window().then(win => { expect(win.document.title).to.equal('Title'); })`. .document() accesses document: `cy.document().its('body').should('exist')`.

window()accesseswindowobject
Q 116

How do you test real-time applications (websockets) in Cypress?

Mock WebSocket events: `cy.window().then(win => { const event = new MessageEvent('message', {data: 'test'}); win.dispatchEvent(event); })`. Or use cy.intercept() with SSE.

MockWebSocketeventswindow()
Q 117

What is the purpose of experimentalFetchPolyfill?

experimentalFetchPolyfill enables cy.intercept() to work with fetch() API. Enable in cypress.config.js: `e2e: { experimentalFetchPolyfill: true }`.

experimentalFetchPolenablesintercept()work
Q 118

How do you implement data factories in Cypress tests?

Create factory functions to generate test data: `function createUser() { return {id: 1, name: 'John', email: 'john@test.com'}; }`. Use in tests with cy.request() to create via API.

Createfactoryfunctionsgenerate
Q 119

What is the purpose of Cypress debugging modes (headed vs headless)?

Headed mode (--headed) opens browser for visual debugging. Headless mode runs without browser (default in CI). Use headed for interactive debugging, headless for CI/CD.

Headedmode(--headed)opens
Q 120

How do you handle retries for API calls in Cypress?

Create custom retry logic: `function apiCall() { return cy.request({...}).then(resp => resp.status === 200 ? resp : apiCall()); }`. Or use cy.request() with retry-after header handling.

Createcustomretrylogic
Q 121

What is the purpose of cy.exec() and when should it be used?

cy.exec() runs shell commands: `cy.exec('npm run migrate').then(result => { expect(result.code).to.equal(0); })`. Use for setup/teardown (database migration, file operations).

exec()runsshellcommands
Q 122

How do you optimize Cypress test performance?

Strategies: use cy.session() to cache auth, minimize network calls, mock APIs with cy.intercept(), avoid hard waits, use data-testid selectors, run tests in parallel with cypress-parallel plugin.

Strategiessession()cacheauth
Q 123

What is the purpose of the onBeforeLoad and onBeforeUnload hooks?

onBeforeLoad runs before page loads: `cy.visit('/page', {onBeforeLoad: (win) => { win.localStorage.setItem('key', 'value'); }})`. Useful for pre-setting state before page loads.

onBeforeLoadrunsbeforepage
Q 124

How do you test GraphQL queries in Cypress?

Mock GraphQL requests: `cy.intercept('POST', '/graphql', {data: {user: {id: 1, name: 'John'}}})`. Or test real queries: `cy.request({method: 'POST', url: '/graphql', body: {query: '...'}})`.

MockGraphQLrequestsintercept('POST'
Q 125

What is the purpose of screenshotOnRunFailure?

screenshotOnRunFailure automatically captures screenshots on test failure. Configure in cypress.config.js: `screenshotOnRunFailure: true` (default). Useful for debugging failures.

screenshotOnRunFailuautomaticallycapturesscreenshots
Q 126

How do you implement a test retry strategy for flaky tests?

Configure retries in cypress.config.js: `retries: { runMode: 2, openMode: 0 }`. Use for flaky tests, but prefer fixing root causes: improve selectors, mock APIs, explicit waits.

Configureretriescypressconfig
Q 127

What is the purpose of cy.scrollTo()?

cy.scrollTo() scrolls window or element: `cy.scrollTo('bottom')`, `cy.scrollTo(0, 500)`. Or on element: `cy.get('#container').scrollTo('right')`.

scrollTo()scrollswindowelement
Q 128

How do you test infinite scroll in Cypress?

Scroll to bottom and verify new content loads: `cy.get('body').scrollTo('bottom'); cy.wait('@load'); cy.get('.item').should('have.length.greaterThan', initialCount)`.

Scrollbottomverifycontent
Q 129

What is the purpose of isInteractive in Cypress config?

isInteractive indicates if running in interactive mode (Test Runner). Configure: `Cypress.config('isInteractive')`. Use to skip certain tests in CI, enable debug features in interactive mode.

isInteractiveindicatesrunninginteractive
Q 130

How do you handle file downloads in Cypress?

Verify download folder: `cy.get('a').click(); cy.readFile('cypress/downloads/file.pdf').should('exist')`. Or check headers: `cy.intercept('GET', '/download', (req) => { expect(req.headers).to.have.property('content-disposition'); })`.

Verifydownloadfolderget('a')
Q 131

What is the purpose of configFile in Cypress?

configFile specifies custom config file: `cypress run --config-file cypress.staging.config.js`. Useful for running tests against different environments.

configFilespecifiescustomconfig
Q 132

How do you implement BDD-style assertions in Cypress?

Cypress uses Chai BDD by default: `expect(value).to.equal(expected)`. Also supports TDD: `assert.equal(value, expected)`. Use appropriate style for readability.

CypressChaidefault`expect(value)
Q 133

What is the purpose of cy.clock() and cy.tick()?

cy.clock() freezes time: `cy.clock()`. cy.tick() advances time: `cy.tick(5000)`. Useful for testing timer-dependent code, debounces, throttles: `cy.tick(500); cy.get('result').should('exist')`.

clock()freezestimeclock()`
Q 134

How do you test OAuth flows in Cypress?

Mock OAuth responses: `cy.intercept('POST', '/oauth/token', {access_token: 'token'})`. Or use cy.session() to cache authenticated state across tests.

MockOAuthresponsesintercept('POST'
Q 135

What is the purpose of experimentalRunAllSpecs?

experimentalRunAllSpecs runs all specs in a single browser session. Configure in cypress.config.js: `experimentalRunAllSpecs: true`. Speeds up test suite but shares state between specs.

experimentalRunAllSprunsspecssingle
Q 136

How do you implement custom error handling in Cypress?

Use Cypress.on('uncaught:exception') to handle errors: `Cypress.on('uncaught:exception', (err, runnable) => { if (err.message.includes('expected')) return false; })`. Return false to fail test.

Cypresson('uncaughtexception')handle
Q 137

What is the purpose of .spread() in Cypress?

.spread() spreads array elements as arguments: `cy.get('input').invoke('val').spread((input) => { expect(input).to.equal('value'); })`. Rarely used, mostly for complex chains.

spread()spreadsarrayelements
Q 138

How do you test JWT authentication in Cypress?

Store JWT in localStorage/sessionStorage: `cy.window().then(win => { win.localStorage.setItem('token', jwtToken); })`. Or use cy.request() with Authorization header.

StorelocalStorage/sessionwindow()then(win
Q 139

What is the purpose of .as() for aliases?

.as() creates aliases for elements: `cy.get('button').as('submitBtn'); cy.get('@submitBtn').click();`. Or for routes: `cy.intercept(...).as('getUsers'); cy.wait('@getUsers')`.

as()createsaliaseselements
Q 140

How do you test multi-language applications in Cypress?

Set language before loading: `cy.visit('/app', {qs: {lang: 'es'}})`. Or test language switching: `cy.get('[data-lang="es"]').click(); cy.get('h1').should('contain.text', 'Spanish text')`.

languagebeforeloadingvisit('/app'
Q 141

What is the purpose of .get() with filters?

Combine with jQuery filters: `cy.get('li:visible').should('have.length', 3)` or `cy.get('input:checked').should('have.length.greaterThan', 0)`.

CombinejQueryfiltersget('li
Q 142

How do you handle dynamic timeouts per test?

Set per-command: `cy.get('element', {timeout: 10000})`. Set per-test in beforeEach: `Cypress.config('defaultCommandTimeout', 8000)`. Reset after: `Cypress.config('defaultCommandTimeout', 4000)`.

per-commandget('element'{timeout10000})`
Q 143

What is the purpose of cy.debug()?

cy.debug() pauses execution and opens DevTools: `cy.get('button').debug()`. Similar to cy.pause() but focused on debugging specific commands.

debug()pausesexecutionopens
Q 144

How do you test service worker functionality in Cypress?

Mock service worker behavior using MSW (Mock Service Worker) library. Or test offline: `cy.visit('/app'); Cypress.automation('take:screenshot')`. Service workers are complex to test in Cypress.

Mockserviceworkerbehavior
Q 145

What is the purpose of experimentalNetworkStubbing?

experimentalNetworkStubbing is the newer API for cy.intercept(). Already used in modern Cypress versions. Configure advanced network stubbing behaviors.

experimentalNetworkSnewerintercept()Already
Q 146

How do you implement parameterized tests in Cypress?

Use test data arrays: `const users = [{...}, {...}]; users.forEach(user => { it(`should login as ${user.name}`, () => { cy.login(user); }); })`.

testdataarrays`const
Q 147

What is the purpose of cy.state()?

cy.state() accesses internal Cypress state (rarely needed): `cy.state('window')`. Mostly for debugging, not recommended for production tests.

state()accessesinternalCypress
Q 148

How do you test drag-and-drop functionality?

Use cy.trigger() to simulate drag events: `cy.get('.draggable').trigger('dragstart'); cy.get('.droppable').trigger('drop')`. Or use cypress-drag-drop plugin for easier syntax.

trigger()simulatedragevents
Q 149

What is the purpose of .get() with :not() selector?

Exclude elements: `cy.get('li:not(.active)')` selects non-active list items. Useful for testing negative cases or excluding specific elements.

Excludeelementsget('linot(
Q 150

How do you set up a comprehensive Cypress test strategy?

Strategy: define test pyramid (unit, integration, e2e), prioritize critical paths, use Page Object Model, implement CI/CD, monitor flaky tests, maintain test data, document best practices, review coverage.

Strategydefinetestpyramid