Cypress Middle cheat sheet: interview answers

Every question of this level with its correct answer and explanation, on one page for a quick review before the interview.

  1. 1. In Cypress 12+, what is the difference between queries and action commands?

    Correct answer: Queries like get are retried; actions like click run once

    Queries re-run until assertions pass. Actions such as .click() or .type() aren't retried, though they wait for actionability first.

  2. 2. In cy.get('.list').find('li').should('have.length', 3), what is retried?

    Correct answer: The whole chain of queries before the assertion

    Since Cypress 12, a failing assertion re-runs the chain of linked queries, so newly rendered elements are found.

  3. 3. Why can an action in the middle of a chain break retrying?

    cy.get("input").type("abc").should("have.value", "abc");

    Correct answer: Actions aren't retried, so only queries after them retry

    If the .type() happened on an element that re-rendered, retrying the assertion can't redo the typing. Split long chains around actions.

  4. 4. What does .should(callback) add compared with .then(callback)?

    cy.get(".total").should(($el) => {
      expect(parseFloat($el.text())).to.be.greaterThan(0);
    });

    Correct answer: The callback is retried until its expectations pass

    Use .should() for checks that may need time. .then() runs once and is for working with a value.

  5. 5. What does .its('length') do?

    Correct answer: Gets a property of the subject, with retrying

    .its() is a query, so cy.get('li').its('length').should('be.gt', 2) retries. .invoke() calls a method on the subject.

  6. 6. How do you assert on the response of an intercepted request?

    cy.wait("@saveOrder").its("response.statusCode").should("eq", 201);

    Correct answer: Wait on the alias and check properties of the interception

    cy.wait('@alias') yields an object with request and response, so body, headers and status can all be asserted.

  7. 7. How do you check the body a form sends to the API?

    Correct answer: Intercept it and assert interception.request.body

    This catches frontend bugs like wrong field names or types that a stubbed backend would accept silently.

  8. 8. How do you simulate a slow API in Cypress?

    Correct answer: cy.intercept('/api/*', (req) => req.reply({ delay: 3000 }))

    Delays let you test loading states and timeouts. throttleKbps simulates slow bandwidth.

  9. 9. How do you simulate a network failure for a request?

    Correct answer: cy.intercept('/api/data', { forceNetworkError: true })

    It makes the request fail as if the connection dropped, so you can check offline or retry handling.

  10. 10. How do you change part of a real response with cy.intercept?

    cy.intercept("GET", "/api/user", (req) => {
      req.continue((res) => {
        res.body.plan = "pro";
      });
    });

    Correct answer: Continue the request and modify the response in the callback

    Partial stubbing keeps the real backend in play while forcing one condition, like a paid plan or a feature flag.

  11. 11. Why must cy.intercept be defined before the action that triggers the request?

    Correct answer: Requests sent before it was registered won't be caught

    Register intercepts first, then visit or click. Otherwise a fast request slips through and cy.wait times out.

  12. 12. Are aliases shared between tests?

    Correct answer: No, aliases are reset before each test

    Define aliases in beforeEach if all tests need them. Using this.alias needs function () {} tests, not arrow functions.

  13. 13. What does the validate option of cy.session do?

    Correct answer: Checks the restored session still works, recreating it if not

    If a token expired, validation fails and Cypress runs the setup again, preventing confusing failures later in the test.

  14. 14. What does cacheAcrossSpecs: true on cy.session do?

    Correct answer: Reuses the session in other spec files during the run

    It avoids logging in once per spec file, which speeds up large suites.

  15. 15. What does cy.origin() solve?

    Correct answer: Running commands on another domain, e.g. an SSO login page

    Cypress normally restricts a test to one origin. cy.origin lets you interact with a third-party login page, then return.

  16. 16. How do you handle a link that opens a new tab in Cypress?

    Correct answer: Check the href or remove target; tabs aren't supported

    Cypress controls one tab. Checking the link's href or removing target=_blank before clicking tests the behaviour in place.

  17. 17. How do you interact with content inside an iframe in Cypress?

    Correct answer: Get the iframe's body and wrap it, or use a plugin

    A common helper gets iframe.contentDocument.body, waits for it to be non-empty, then uses cy.wrap() to query inside.

  18. 18. How do you query elements inside shadow DOM?

    Correct answer: includeShadowDom: true in config or .shadow()

    With the config option, cy.get searches shadow roots. .shadow() steps into a specific host's shadow root.

  19. 19. How do you add TypeScript types for a custom command cy.login?

    Correct answer: Declare it in the Cypress.Chainable interface

    Extending namespace Cypress { interface Chainable { login(...): Chainable<void> } } gives autocompletion and type checks.

  20. 20. When should you use Cypress.Commands.overwrite?

    Correct answer: Rarely, e.g. to add logging or defaults to a built-in command

    Overwriting changes behaviour everywhere, which surprises readers. Prefer new commands with clear names.

  21. 21. Where are cy.task handlers registered?

    Correct answer: In setupNodeEvents in the Cypress config

    on('task', { seedDb() { ... } }) runs in Node, where database clients and the file system are available.

  22. 22. Why seed test data with cy.task or API calls instead of the UI?

    Correct answer: It's faster, more stable and focuses the test on one feature

    If creating an order through five screens is not what the test checks, set it up directly and test only the behaviour that matters.

  23. 23. What are "app actions" in Cypress testing?

    Correct answer: Calling app code directly, e.g. via window, to set up state

    Exposing a store or helper on window in test builds lets tests set state instantly. It's an alternative to big page objects.

  24. 24. What does cy.window() give you?

    Correct answer: The app's window, to read or call things on it

    For example cy.window().its('store').invoke('dispatch', action) sets app state in tests that support it.

  25. 25. How do you test that window.open was called with the right URL?

    cy.window().then((win) => {
      cy.stub(win, "open").as("open");
    });
    cy.contains("Share").click();
    cy.get("@open").should("be.calledWith", "https://example.com/share");

    Correct answer: Stub win.open and assert on the alias

    Stubbing replaces the real call, so no tab opens, and Sinon assertions check the arguments.

  26. 26. What is the difference between cy.spy and cy.stub?

    Correct answer: A spy records calls and keeps the original; a stub replaces it

    Use a spy to check an analytics call happened, a stub to prevent a side effect or force a return value.

  27. 27. How do you test that a session expires after 30 minutes of inactivity?

    Correct answer: cy.clock() then cy.tick(30 * 60 * 1000) and assert logout

    Fake timers make long waits instant. Install the clock before visiting, so the app picks it up.

  28. 28. How do you read a downloaded file in a Cypress test?

    Correct answer: cy.readFile('cypress/downloads/report.csv')

    Downloads go to the configured downloadsFolder. cy.readFile retries until the file exists, then you assert on its content.

  29. 29. How can you add accessibility checks to Cypress tests?

    Correct answer: Use cypress-axe to run axe-core on the page

    cy.injectAxe() then cy.checkA11y() reports violations like missing labels. Manual checks are still needed for others.

  30. 30. What does visual regression testing require in Cypress?

    Correct answer: A plugin or service that compares screenshots

    Cypress takes screenshots but doesn't diff them. Plugins or services store baselines and highlight pixel differences.

  31. 31. How do you mount a React component that needs a router and store in component tests?

    Correct answer: Wrap it in providers in a custom mount command

    A custom cy.mount that wraps components with router, theme and store providers keeps each test short.

  32. 32. Why does Cypress recommend against the Page Object pattern in some cases?

    Correct answer: App actions and custom commands can be simpler and faster

    Page objects aren't forbidden, but deep hierarchies add indirection. Short custom commands and direct state setup often read better.

  33. 33. What is "conditional testing" and why is it discouraged?

    cy.get("body").then(($body) => {
      if ($body.find(".cookie-banner").length) {
        cy.get(".cookie-banner button").click();
      }
    });

    Correct answer: Branching on DOM state is flaky; the DOM may still change

    The banner may appear a moment later. Control the state instead, for example by setting the consent cookie before visiting.

  34. 34. Why shouldn't you mix async/await with Cypress commands?

    Correct answer: Commands aren't Promises; awaiting them breaks the queue

    Cypress commands are enqueued and chainable. Use .then() to work with values; cy.wrap() can wrap a real Promise.

  35. 35. What does cy.wrap() do?

    Correct answer: Turns a value or Promise into a Cypress subject

    For example cy.wrap(apiClient.getUser()) waits for the Promise and lets you chain assertions.

  36. 36. How do you call an API with auth in cy.request?

    Correct answer: Pass headers or use auth in the options object

    cy.request({ url, headers: { Authorization: 'Bearer ...' } }). It also sends the browser's cookies for that domain.

  37. 37. What does failOnStatusCode: false in cy.request allow?

    Correct answer: Asserting on 4xx or 5xx responses instead of failing

    By default non-2xx/3xx responses fail the test. Turn it off when the error response is what you want to check.

  38. 38. How do you run Cypress tests against different environments?

    Correct answer: Override baseUrl and env values via config files or CLI

    --config baseUrl=..., --env or CYPRESS_ variables let one suite run against local, staging and preview deployments.

  39. 39. What is a risk of turning testIsolation off?

    Correct answer: State leaks between tests, so order and retries matter

    Without isolation, the page and storage carry over. It can speed up some flows but makes failures harder to understand.

  40. 40. What is the difference between before and beforeEach?

    Correct answer: before runs once per block, beforeEach before every test

    With test isolation, state from before is cleared before each test, so per-test setup usually belongs in beforeEach.

  41. 41. What does retries: { runMode: 2 } mean?

    Correct answer: Failed tests are retried up to two times in cypress run

    Retries reduce noise from rare glitches. Tests that pass only on retry are flaky and should be fixed.

  42. 42. What causes "element is detached from the DOM" style failures?

    Correct answer: The app re-rendered and replaced the element after it was found

    Since Cypress 12, queries re-run automatically, which removes most of these. Actions on stale elements can still fail if chains are long.

  43. 43. How can animations cause flaky Cypress tests?

    Correct answer: Elements move or are covered while Cypress tries to act

    Cypress waits for elements to stop animating, but long or looping animations still cause trouble. Disable them in test builds.

  44. 44. How do you parallelize Cypress tests without Cypress Cloud?

    Correct answer: Split specs across CI machines, e.g. with a split plugin

    --parallel relies on a recording service. Community tools split specs by name or timing across CI jobs.

  45. 45. Why use the official cypress/included Docker image in CI?

    Correct answer: Cypress, browsers and dependencies come preinstalled

    Matching the image version to your Cypress version avoids missing system libraries and makes runs consistent.

  46. 46. Which CI artifacts help most when a Cypress run fails?

    Correct answer: Screenshots, videos and the run's reporter output

    Uploading cypress/screenshots and cypress/videos lets anyone see the failure without rerunning it.

  47. 47. What does cy.log() do?

    Correct answer: Prints a message in the Cypress command log

    It's useful to mark steps in long tests. For terminal output in cypress run, use a cy.task that calls console.log.

  48. 48. How do you clear cookies or storage inside a test?

    Correct answer: cy.clearCookies() and cy.clearLocalStorage()

    Test isolation clears them before each test; these commands help when a test needs a clean state halfway through.

  49. 49. How do you test responsive layouts in Cypress?

    Correct answer: Set cy.viewport per test or loop over sizes

    A loop with cy.viewport(w, h) and assertions per breakpoint checks menus and layout at each size.

  50. 50. What does cy.contains('button', /^Save$/) add with a regex?

    Correct answer: Exact matching of the text, not a substring

    A plain string matches substrings, so "Save draft" would also match "Save". A regex makes the match precise.

  51. 51. What is the difference between .within() and .find()?

    Correct answer: .within scopes all following commands in a callback; .find one query

    .within is handy for forms with many fields; .find is a single scoped query.

  52. 52. How do you get a cookie value to assert on it?

    Correct answer: cy.getCookie('session').should('exist')

    cy.getCookie yields an object with value, httpOnly, secure and more, so security flags can be checked.

  53. 53. How can code coverage be collected from Cypress tests?

    Correct answer: Instrument the app and use the code coverage plugin

    The app is built with instrumentation (e.g. Istanbul) and the plugin merges coverage from all specs into a report.

  54. 54. Why are long, multi-page end-to-end tests harder to maintain?

    Correct answer: One change breaks them and failures are hard to locate

    Shorter tests with direct setup fail closer to the cause and run faster in parallel.

  55. 55. What happens to the command queue when an assertion inside it fails?

    Correct answer: The test stops and later commands don't run

    Cypress fails fast within a test. Split independent checks into separate tests if you need all results.

  56. 56. What does cy.intercept route matching use by default for URLs?

    Correct answer: Glob patterns or exact strings, plus regex if you pass one

    For example '/api/users/*' or { method: 'POST', url: /\/api\/orders/ }. Narrow matching avoids catching unrelated requests.

  57. 57. If two intercepts match the same request, which handler runs first?

    Correct answer: The most recently defined one

    Newer intercepts take precedence, which lets a test override a general stub from beforeEach with a specific one.

  58. 58. How do you test a request that should NOT happen?

    Correct answer: Intercept it with an alias and assert the call count is 0

    cy.get('@track.all').should('have.length', 0) checks no tracking call fired, for example when consent was declined.

  59. 59. How do you load a fixture and use it in assertions?

    cy.fixture("user.json").then((user) => {
      cy.get("[data-cy=name]").should("have.text", user.name);
    });

    Correct answer: cy.fixture with .then, or alias it with .as()

    Aliasing with .as('user') and this.user also works in function () {} tests.

  60. 60. What is a good way to keep Cypress specs fast as a suite grows?

    Correct answer: Seed via API, stub slow third parties, keep tests short

    Most time goes into UI setup and waiting. Direct setup and focused tests keep runs short.

  61. 61. Why does Cypress run each spec in a fresh browser context?

    Correct answer: To isolate specs so one can't affect another

    Fresh contexts prevent leaked state between files. Combined with test isolation, each test starts clean.

  62. 62. How do you test a third-party payment iframe in Cypress?

    Correct answer: Use test mode or stubs; run the full flow sparingly

    Cross-origin iframes are hard to drive. Stubbing the payment step for most tests and one sandbox flow is a common split.

  63. 63. How can a Cypress test fail if the app logs console errors?

    Correct answer: Spy on console.error in onBeforeLoad and assert

    cy.visit(url, { onBeforeLoad(win) { cy.spy(win.console, 'error').as('err') } }) then assert on @err.

  64. 64. What is onBeforeLoad in cy.visit useful for?

    Correct answer: Changing window before app scripts run, e.g. stubs

    It's the place to stub browser APIs like geolocation or set localStorage flags before the app reads them.

  65. 65. How do you test geolocation-based features in Cypress?

    Correct answer: Stub navigator.geolocation in onBeforeLoad

    Stubbing getCurrentPosition to call back with fixed coordinates makes the test deterministic.

  66. 66. What's the role of defineConfig in cypress.config.ts?

    Correct answer: Typed configuration helper with editor autocompletion

    It returns the config unchanged but gives TypeScript types for options like e2e, component and setupNodeEvents.

  67. 67. How do you run Cypress against a local dev server in CI?

    Correct answer: Start the server, wait for its URL, then run Cypress

    Tools like start-server-and-test or CI service containers start the app and wait until it responds.

  68. 68. Why should tests avoid depending on the exact order of API items?

    Correct answer: Order may differ between runs unless the API guarantees it

    Assert on items by content or sort explicitly. Otherwise tests fail when the backend returns the same items in another order.

  69. 69. How do you assert that a button becomes enabled after a form is valid?

    Correct answer: .should('be.enabled'), which retries until valid

    Retrying assertions cover the moment between typing and validation finishing.

  70. 70. What does cy.document() yield?

    Correct answer: The document object of the app

    It's useful for checking things like document.title or the lang attribute.

  71. 71. How do you test keyboard navigation in Cypress?

    Correct answer: Press Tab (natively or via a plugin) and check focus

    Asserting cy.focused() after each key checks focus order and visible focus.

  72. 72. What does cy.focused() yield?

    Correct answer: The element that currently has focus

    Combined with key presses, it checks that focus moves where expected, for example into an opened dialog.

  73. 73. When does it make sense to use cy.request for a whole test instead of the UI?

    Correct answer: When testing API behaviour, not the user interface

    Cypress can test APIs directly. For larger API suites, a dedicated API testing tool may fit better.

  74. 74. How do you share setup like login across many specs?

    Correct answer: A custom command or cy.session called in beforeEach

    Central setup keeps specs short and changes to login need editing in one place.

  75. 75. What does Cypress.env() read in the browser?

    Correct answer: Values from config, cypress.env.json or CYPRESS_ vars

    Only explicitly exposed values reach the browser. Avoid putting secrets there if specs run with screenshots or videos shared widely.

  76. 76. What does cy.writeFile do?

    Correct answer: Writes data to a file from the test

    It can save generated data or fixtures. Files go through the Node process, relative to the project root.

  77. 77. How do you assert a CSS property, like a colour?

    Correct answer: .should('have.css', 'color', 'rgb(255, 0, 0)')

    Browsers report computed colours as rgb(). Checking style is fragile; use it for important visual states.