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. In Cypress 12+, what is the difference between queries and action commands?
Correct answer: Queries like
getare retried; actions likeclickrun onceQueries re-run until assertions pass. Actions such as
.click()or.type()aren't retried, though they wait for actionability first.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. 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. 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. What does
.its('length')do?Correct answer: Gets a property of the subject, with retrying
.its()is a query, socy.get('li').its('length').should('be.gt', 2)retries..invoke()calls a method on the subject.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 withrequestandresponse, so body, headers and status can all be asserted.7. How do you check the body a form sends to the API?
Correct answer: Intercept it and assert
interception.request.bodyThis catches frontend bugs like wrong field names or types that a stubbed backend would accept silently.
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.
throttleKbpssimulates slow bandwidth.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. 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. Why must
cy.interceptbe 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.waittimes out.12. Are aliases shared between tests?
Correct answer: No, aliases are reset before each test
Define aliases in
beforeEachif all tests need them. Usingthis.aliasneedsfunction () {}tests, not arrow functions.13. What does the
validateoption ofcy.sessiondo?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. What does
cacheAcrossSpecs: trueoncy.sessiondo?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. 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.originlets you interact with a third-party login page, then return.16. How do you handle a link that opens a new tab in Cypress?
Correct answer: Check the
hrefor removetarget; tabs aren't supportedCypress controls one tab. Checking the link's
hrefor removingtarget=_blankbefore clicking tests the behaviour in place.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 usescy.wrap()to query inside.18. How do you query elements inside shadow DOM?
Correct answer:
includeShadowDom: truein config or.shadow()With the config option,
cy.getsearches shadow roots..shadow()steps into a specific host's shadow root.19. How do you add TypeScript types for a custom command
cy.login?Correct answer: Declare it in the
Cypress.ChainableinterfaceExtending
namespace Cypress { interface Chainable { login(...): Chainable<void> } }gives autocompletion and type checks.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. Where are
cy.taskhandlers registered?Correct answer: In
setupNodeEventsin the Cypress configon('task', { seedDb() { ... } })runs in Node, where database clients and the file system are available.22. Why seed test data with
cy.taskor 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. What are "app actions" in Cypress testing?
Correct answer: Calling app code directly, e.g. via
window, to set up stateExposing a store or helper on
windowin test builds lets tests set state instantly. It's an alternative to big page objects.24. What does
cy.window()give you?Correct answer: The app's
window, to read or call things on itFor example
cy.window().its('store').invoke('dispatch', action)sets app state in tests that support it.25. How do you test that
window.openwas 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.openand assert on the aliasStubbing replaces the real call, so no tab opens, and Sinon assertions check the arguments.
26. What is the difference between
cy.spyandcy.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. How do you test that a session expires after 30 minutes of inactivity?
Correct answer:
cy.clock()thency.tick(30 * 60 * 1000)and assert logoutFake timers make long waits instant. Install the clock before visiting, so the app picks it up.
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.readFileretries until the file exists, then you assert on its content.29. How can you add accessibility checks to Cypress tests?
Correct answer: Use
cypress-axeto run axe-core on the pagecy.injectAxe()thency.checkA11y()reports violations like missing labels. Manual checks are still needed for others.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. 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
mountcommandA custom
cy.mountthat wraps components with router, theme and store providers keeps each test short.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. 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. Why shouldn't you mix
async/awaitwith 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. 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. How do you call an API with auth in
cy.request?Correct answer: Pass headers or use
authin the options objectcy.request({ url, headers: { Authorization: 'Bearer ...' } }). It also sends the browser's cookies for that domain.37. What does
failOnStatusCode: falseincy.requestallow?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. How do you run Cypress tests against different environments?
Correct answer: Override
baseUrland env values via config files or CLI--config baseUrl=...,--envorCYPRESS_variables let one suite run against local, staging and preview deployments.39. What is a risk of turning
testIsolationoff?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. What is the difference between
beforeandbeforeEach?Correct answer:
beforeruns once per block,beforeEachbefore every testWith test isolation, state from
beforeis cleared before each test, so per-test setup usually belongs inbeforeEach.41. What does
retries: { runMode: 2 }mean?Correct answer: Failed tests are retried up to two times in
cypress runRetries reduce noise from rare glitches. Tests that pass only on retry are flaky and should be fixed.
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. 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. How do you parallelize Cypress tests without Cypress Cloud?
Correct answer: Split specs across CI machines, e.g. with a split plugin
--parallelrelies on a recording service. Community tools split specs by name or timing across CI jobs.45. Why use the official
cypress/includedDocker 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. Which CI artifacts help most when a Cypress run fails?
Correct answer: Screenshots, videos and the run's reporter output
Uploading
cypress/screenshotsandcypress/videoslets anyone see the failure without rerunning it.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 acy.taskthat callsconsole.log.48. How do you clear cookies or storage inside a test?
Correct answer:
cy.clearCookies()andcy.clearLocalStorage()Test isolation clears them before each test; these commands help when a test needs a clean state halfway through.
49. How do you test responsive layouts in Cypress?
Correct answer: Set
cy.viewportper test or loop over sizesA loop with
cy.viewport(w, h)and assertions per breakpoint checks menus and layout at each size.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. What is the difference between
.within()and.find()?Correct answer:
.withinscopes all following commands in a callback;.findone query.withinis handy for forms with many fields;.findis a single scoped query.52. How do you get a cookie value to assert on it?
Correct answer:
cy.getCookie('session').should('exist')cy.getCookieyields an object withvalue,httpOnly,secureand more, so security flags can be checked.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. 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. 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. What does
cy.interceptroute 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. 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
beforeEachwith a specific one.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. 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.fixturewith.then, or alias it with.as()Aliasing with
.as('user')andthis.useralso works infunction () {}tests.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. 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. 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. How can a Cypress test fail if the app logs console errors?
Correct answer: Spy on
console.errorinonBeforeLoadand assertcy.visit(url, { onBeforeLoad(win) { cy.spy(win.console, 'error').as('err') } })then assert on@err.64. What is
onBeforeLoadincy.visituseful for?Correct answer: Changing
windowbefore app scripts run, e.g. stubsIt's the place to stub browser APIs like geolocation or set
localStorageflags before the app reads them.65. How do you test geolocation-based features in Cypress?
Correct answer: Stub
navigator.geolocationinonBeforeLoadStubbing
getCurrentPositionto call back with fixed coordinates makes the test deterministic.66. What's the role of
defineConfigincypress.config.ts?Correct answer: Typed configuration helper with editor autocompletion
It returns the config unchanged but gives TypeScript types for options like
e2e,componentandsetupNodeEvents.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-testor CI service containers start the app and wait until it responds.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. How do you assert that a button becomes enabled after a form is valid?
Correct answer:
.should('be.enabled'), which retries until validRetrying assertions cover the moment between typing and validation finishing.
70. What does
cy.document()yield?Correct answer: The
documentobject of the appIt's useful for checking things like
document.titleor thelangattribute.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. 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. When does it make sense to use
cy.requestfor 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. How do you share setup like login across many specs?
Correct answer: A custom command or
cy.sessioncalled inbeforeEachCentral setup keeps specs short and changes to login need editing in one place.
75. What does
Cypress.env()read in the browser?Correct answer: Values from config,
cypress.env.jsonorCYPRESS_varsOnly explicitly exposed values reach the browser. Avoid putting secrets there if specs run with screenshots or videos shared widely.
76. What does
cy.writeFiledo?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. 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.