QA Interview Hub · Knowledge base · Quizzes · Українська
35 Cypress questions that come up in QA interviews, with short answers. Open the topic in the knowledge base for a deeper explanation.
The cypress.config.ts file exports defineConfig({ ... }). In the e2e block I set baseUrl (so cy.visit('/login') works without a full URL), specPattern, setupNodeEvents for plugins and Node tasks, and viewportWidth and viewportHeight. env holds secrets that a test reads with cy.env(['apiKey']), and public values go into expose and are read with Cypress.expose('apiUrl') (Cypress.env() was removed in Cypress 16); secrets are better taken from CI variables. retries: { runMode: 2, openMode: 0 } reruns failed tests only in cypress run, not in the interactive mode. I also often change defaultCommandTimeout, video and screenshotOnRunFailure.
Cypress works as two processes. The first is a Node process: it launches the browser, manages network interception and does everything the browser can't, such as working with files or a database through cy.task. The second is the browser itself, where two iframes live in one tab: my test in one and the application in the other. That is why the test has direct access to the DOM. Between Node and the browser there is a WebSocket. Requests are intercepted by cy.intercept: in Firefox, WebKit and Electron through the proxy in Node, and since Cypress 16 in Chrome, Chromium and Edge right in the browser's network.
An e2e test opens the whole application and walks through a scenario like a user. Component testing mounts a single component with cy.mount in a real browser, without the rest of the application and without a backend. It is much faster and convenient for checking different states of a component, while e2e remains for the key end-to-end scenarios.
Cypress uses the Mocha interface: describe (or context, which is the same) groups tests and can be nested, it (or specify) declares one test. A spec is a file that falls under specPattern; for e2e the default is cypress/e2e/**/*.cy.{js,jsx,ts,tsx}. That is why login.js without the .cy infix is silently ignored, and each spec runs on its own, isolated from the others. The pattern can be changed in the config, and exclusions are set by excludeSpecPattern. Shared code (hooks, commands) goes into the support file, which is loaded before every spec.
cypress open starts the interactive Test Runner: a spec list, browser choice, the Command Log, time travel with DOM snapshots, an automatic rerun when a file changes. It is the mode for developing and debugging tests. cypress run executes the specs in the terminal without a window: headless by default, with a console summary, screenshots on failure and an exit code from the result, so it is the CI mode. The config is the same, but retries are often different: retries.runMode for run and retries.openMode for open. Without --browser, run uses the built-in Electron, which is deprecated in Cypress 16, so in CI it is better to name the browser explicitly.
For a Promise there is cy.wrap: I wrap the Promise, Cypress waits for it in the queue and passes the value on. And code that must run in Node, such as database queries, I move into cy.task, which returns the result straight into the test. The main thing is not to mix the Cypress queue and await in one place, because the order of execution becomes unpredictable.
A subject is the result that one command passes to the next one in the chain. For example, cy.get passes the found elements, its length passes a number, invoke text passes a string. Some commands start a new chain, like cy.get or cy.request, and others work with what came from the previous one, like find, click or should.
The .as('name') method gives a name to the result of the previous command (an element, a request, a fixture) so that you can refer to it later with cy.get('@name'), or cy.wait('@name') for an intercepted request. It is a way to share values between commands without JavaScript variables, which do not work through the asynchronous queue. An element alias is looked up again on use, so it does not hold stale DOM. For values that must be compared in different places of a test, aliases read better than nested .then calls. An alias does not survive the test boundary: it is reset between tests.
cy.wrap(value) makes any value (an object, an array, a Promise) the subject of the chain, so commands and should work on it. its('prop') reads a property of the subject without calling it and is retried, for example its('length') or its('body.name') for a response. invoke('fn', ...args) calls a method of the subject and passes the result on: invoke('text') or invoke('val'). each(callback) goes through every element of a list and leaves the subject unchanged. Simple assertions are better kept as should('have.length') and should('have.text'), and the listed commands are for reaching a value.
First I collect evidence: a screenshot on failure, video (it has to be turned on explicitly, because it has been off since version 13), and Test Replay if there is Cloud. Then I reproduce it: I run the spec dozens of times in a loop. Next I check the typical causes: hard cy.wait calls, actions before the API response, shared data, animations, an intercept registered after the action. Retries in runMode help to survive until the release, but they don't cure anything, so I investigate each such test.
Queries are requests to the DOM: get, find, contains, its. They are repeated until the assertion after them passes. Assertions, should and and, are what trigger those repeats. Actions, click, type, select, wait for the element to become actionable but run once, because a repeated click could break the application's state.
cy.get(selector) searches by CSS selector and returns elements; cy.contains(text) finds an element that contains the text (it does not check visibility: add .should("be.visible") for that) (you can narrow it with a selector: cy.contains('button', 'Save')). Both commands keep retrying until the element appears or defaultCommandTimeout (4 s) passes. data-cy (or data-testid) attributes are added to the markup specially for tests: a change of classes, styles or text does not touch them. That is why I write cy.get('[data-cy=submit]') and not .btn-primary. Text through contains is handy for checking what the user sees, but it breaks when the copy or localization changes.
For an iframe I take the contentDocument body and wrap it in cy.wrap, or I use the cypress-iframe plugin, but an iframe from another domain is not accessible. Cypress doesn't support new tabs, so I remove target blank or check the href. For uploading files there is the built-in selectFile, and a downloaded file I verify with readFile in the downloads folder.
Within limits the search to one block: I find the right table row by text, and all the commands inside search only in it. Eq, first and last pick by index, but I use them only when the order really matters. Otherwise I narrow by content with contains or filter.
type(text) enters text character by character with keyboard events; special keys are written in braces in the string, for example {enter} or {backspace}. clear() empties the field and is called before type when the value must be replaced rather than extended. check() and uncheck() guarantee the state of a checkbox or radio: if the state is already right, no click is made. select() picks an option of a <select> by value, index or text, and an array allows multiple selection. Before running, every action waits for actionability: the element must be visible, enabled and not covered. The result is checked with should('have.value'), not have.text.
An intercept sees only the requests that happen after it is registered, so I always set it before visit or a click. Otherwise the request slips through and wait fails, which is a frequent cause of flakiness. If there are several intercepts on one URL, the last one defined fires first, and with times one I can build a scenario where an error comes first and then a success.
For simple cases I pass the response as the third argument: a fixture, a status code, a delay. That is how I check how the UI behaves on a five hundred error or on a slow network. If I need to change a real response precisely, I write a handler: I let the request through to the server with req.continue and change one field in the response.
Checking individual fields misses changes you didn't foresee, for example when the backend changed a field's type. So I validate the whole response against a JSON schema: I add chai-json-schema (for schemas newer than draft-04, chai-json-schema-ajv), and I keep the schemas themselves in fixtures. That way the test fails immediately if the contract changed.
I create the needed data through the API in beforeEach, the test itself checks only the UI, and I clean leftovers up through the API at the start, in beforeEach: the Cypress docs advise cleaning state before tests, not in afterEach. This is much faster and more stable than creating everything with clicks. The same approach works in Playwright: test objects can be deleted through the API after every test.
cy.request sends an HTTP request from the Cypress Node server, not from the browser, so the CORS policy does not apply to it, and cy.intercept does not see it. The result is a response object with status, statusText, headers, duration and body, and body is already parsed into an object if the server returned JSON. By default failOnStatusCode is true, so a status outside 2xx/3xx fails the test; for negative scenarios (400, 401, 404) you set failOnStatusCode: false. Browser cookies are added to the request, and the ones that arrive in Set-Cookie are saved back into the browser, which is what a programmatic login before cy.visit relies on.
before runs once before all tests of a describe block, beforeEach before every test. There are also after and afterEach. I put shared setup (open the page, log in, create data) into beforeEach so each test starts from a known state. Since Cypress 12, testIsolation is on by default: before each test cookies, localStorage and sessionStorage are cleared and the page is reset to about:blank. Tests must be independent: you can run them alone, in another order and in parallel, and one failure does not drag the others down. Otherwise a failure is hard to reproduce and the suite becomes flaky.
A fixture is a file with test data (usually JSON) in cypress/fixtures. cy.fixture('user') reads it and yields the content: cy.fixture('user').then((user) => { cy.get('#email').type(user.email); }). You can store it under an alias: cy.fixture('user').as('user') and take it later with cy.get('@user'). Most often I feed a fixture into network stubs: cy.intercept('GET', '/api/users', { fixture: 'users.json' }). This keeps data separate from the test code, easy to change and to reuse. A fixture is not enough for unique values (an email), so I generate those in code.
If every test logs in through the form, it is slow, and a broken form fails the whole suite even though the tests check something else. So I log in through the API and cache the session with cy.session, and I verify the login form itself with one separate test.
For a spec the order is: before (once; first from the support file, then from the spec), then for every test beforeEach (also from the support file first), the test itself and afterEach, and at the end after (once). In nested describe blocks hooks do not replace each other but add up: first the beforeEach of the outer block, then of the inner one. Cleaning up state and preparing data is advised in beforeEach rather than afterEach: if the run is interrupted in the middle of a test, afterEach does not run and the next test starts with dirty state. Tests must not depend on order: each one should create the data it needs, ideally through the API.
I use Page Object: classes with methods for each page, so the locators are collected in one place and a test reads like a scenario. The Cypress team also suggests App Actions: controlling the application's state directly, without the UI. I combine both: I prepare state through the API, and I use Page Object for the actions the test really verifies. This combination is a typical approach in modern frameworks.
I read secrets through cy.env and public settings through Cypress.expose: Cypress.env was removed in version sixteen. Locally they live in cypress.env.json, which isn't committed, and on CI they are passed as environment variables with the CYPRESS_ prefix from the pipeline's secrets. I pick the environment with the env flag, and in setupNodeEvents I set the right baseUrl.
cypress/e2e holds the *.cy.ts specs; cypress/fixtures holds static data for cy.fixture; cypress/support holds the e2e.ts support file, loaded before every spec, and commands.ts with custom commands; cypress/downloads holds files the app downloaded in a test; cypress/screenshots holds failure screenshots and those from cy.screenshot(); cypress/videos holds videos if video is on. The config sits at the root: cypress.config.ts with e2e.baseUrl, specPattern, retries and setupNodeEvents. All paths are changed by settings such as fixturesFolder or screenshotsFolder, and the cypress.json and cypress/integration layout is a thing of the past.
Values from cypress.config can be changed without editing the file. The --config flag takes comma-separated key=value pairs: cypress run --config baseUrl=https://staging.example.com,retries=2. Environment variables with the CYPRESS_ prefix are picked up automatically: CYPRESS_VIEWPORT_WIDTH=800 sets viewportWidth, and the prefix is stripped from the name of the value. For a single test or block the config is passed as the second argument of it or describe: it('name', { retries: 2 }, () => ...). Secrets such as CYPRESS_RECORD_KEY are set as a real CI environment variable, not as a file in the repository. Settings that only concern the environment, such as the location of the binary cache, are set by the CYPRESS_CACHE_FOLDER variable.
On one machine Cypress runs specs sequentially, so parallelisation happens only across several machines. The official way is Cypress Cloud with the record and parallel flags, but beyond the free limit it is paid. For free you can build a matrix in CI and split the specs with the cypress-split plugin. The unit of distribution is a spec file, so I keep specs small.
On a failure in run mode a screenshot is taken automatically, and video has to be turned on explicitly, because it has been off since version thirteen. For HTML reports I use mochawesome, and if I need history and trends, Allure through allure-cypress. For CI systems there is JUnit XML.
The fundamental difference: Cypress runs inside the browser, and Playwright drives it from outside. Everything else follows from that. Cypress has a command queue instead of async/await, one tab, parallelism only across machines and network interception with cy.intercept. Playwright has ordinary promises, multiple tabs and domains, isolated contexts, built-in workers and supports several languages. On the other hand, Cypress has very convenient debugging with time travel.
should('have.text', 'X') and and(...) are implicit assertions: and is an alias of should, and the chain of checks applies to the same subject and is retried until the timeout. A callback in should(cb) is also retried: Cypress repeats the previous query and the callback until it stops throwing. expect() inside then() is an explicit assertion that runs once with the current value, so for dynamic text it is flaky. That is why should with a callback is used for elements that change, and then is left for cases where a value has to be obtained and used further.
In cypress open the Command Log shows every command, and hovering over one gives a DOM snapshot before and after (time travel); clicking a command prints its subject, elements, request and response to the DevTools console. cy.pause() stops execution, and the commands then go step by step. .debug() sets a breakpoint and prints the current subject if DevTools are open. cy.log() writes to the Command Log. The test runs in the browser, so console.log goes to the browser console and not to the terminal; to print a line to the terminal during cypress run, you register a task in setupNodeEvents and call cy.task. In CI, failure screenshots, video if enabled, and Test Replay in Cypress Cloud help.
cy.visit(url) opens a page and waits for the load event; a relative path is taken from baseUrl. By default failOnStatusCode is true, so a response that is not 2xx/3xx fails the test unless { failOnStatusCode: false } is passed. cy.url() returns the whole URL as a string, cy.location('pathname' | 'search' | 'hash') returns a single part, which is handier for checking query parameters. Both are retried, so assertions on the URL wait for the navigation themselves. cy.go('back') and cy.go('forward') move through the history, cy.reload() reloads the page. A page of another origin (scheme, domain or port) can be opened in one test only through cy.origin.
.only next to describe or it runs only that block within the file, the rest of the spec's tests are skipped, and other specs are untouched. That is why a leftover .only silently lowers coverage, and it is caught by a linter (eslint-plugin-mocha or similar) or a CI check. .skip next to describe or it skips the block together with its nested ones; such a test has the pending status in the report, not failed or passed. Cypress gives the separate skipped status to tests that did not run because a hook failed. To choose specs in CI you use --spec rather than editing code.