QA Interview Hub · Knowledge base · Quizzes · Українська

Cypress

Locators and working with the DOM

finding elements and interacting

How does cy.get() differ from .find() and cy.contains()?

cy.get() searches from the document root (scoped inside .within()), .find() among descendants of the previous subject, cy.contains() by text. All three are queries and retry until the timeout. cy.get().get() ignores the previous subject, so nested lookups use .find() or .within(). cy.contains() is case-sensitive and without a selector may hit an element other than the button, so it is combined with a selector.

Cypress · Locators and DOM

The page has three orders; the test checks the price of one but picks every price on the page. Why?

A page shows several orders, each with a [data-cy=price]. The test writes cy.get(order).get(price), and the assertion sometimes fails and sometimes passes by accident. This lesson explains where the search scope of cy.get, .find and cy.contains comes from and how to pick the right command.

How it works and why. cy.get() is a “parent” command: it always starts the search at the document root, not at the previous element of the chain. The exception: inside a .within() block (or with the withinSubject option) the root narrows to the given element. .find() is a “child” command and searches only the descendants of the subject. cy.contains() searches by text; in a chain (.contains(...)) the scope is limited to the subject, while a cy.contains(...) at the start of a chain searches the whole document. All three are queries, so they are retried until the timeout. If the DOM was redrawn between commands, Cypress re-queries the chain of queries from its start, so “stale” elements as in Selenium are rare. One limit: an assertion in the middle of the chain locks the subject, and after it Cypress can no longer requery the page.

Where each command searches

cy.get(sel)the whole document (or within).find(sel)only inside the subjectcy.contains(sel, text)by text; in a chain: inside
Figure 1. The search scope depends on the command type, not on its place in the chain.

Example: the price of the “wrong” order.

Wrong

cy.get().get()

The second get ignores the previous subject and returns the prices of every order on the page. A have.text assertion on several elements compares the joined text and fails, or passes when there is a single order.

Right

cy.get().find()

find takes only the prices inside the found order. The result does not depend on how many orders the page has.

// searches inside order #1042
cy.contains('[data-cy=order]', '#1042')
  .find('[data-cy=price]')
  .should('have.text', '$1,200');

// get after get searches the whole page
cy.get('[data-cy=order]').get('[data-cy=price]');

// contains with a selector: the button, not any text
cy.contains('button', 'Place order').click();

Here cy.contains(selector, text) found the order by its text and find narrowed the search to its price. This combination relies on content, not on the order of rows.

Limits and alternatives. According to the docs, cy.contains is case-sensitive (the matchCase: false option turns that off) and also accepts a regular expression. If several elements match the text it yields one: input[type=submit], button, a and label are preferred, otherwise the deepest element. So cy.contains('Save') without a selector may land on something other than the button. Text is sensitive to copy and localisation changes, so combine it with data-cy for stability.

And in Playwright:

page.locator() searches the page, locator.locator() inside another locator, text is getByText(). The difference is strict mode: if a locator for an action finds several elements, Playwright fails at once. Cypress also needs a single element for click (unless multiple: true), but should happily works with a set.

Common mistakes.

  • .get() inside a chain instead of .find(): the search covers the whole page, so the test is green only while there is a single such element.
  • cy.contains('Text') without a selector on a page where the text is both in a heading and in a button: Cypress picks by its own priority, not by your intent.
  • Keeping a subject in a variable: const order = cy.get(...) stores nothing, because commands are only queued.

Check yourself

What does cy.get('[data-cy=order]').get('[data-cy=price]') find when there are three orders?

Answer

All three prices: the second get searches from the document root and ignores the previous subject. To take the price of one order you need .find() or .within().

Why is cy.contains('button', 'Place order') better than cy.contains('Place order')?

Answer

The selector limits the search to elements of a given kind. Without it a heading or paragraph with the same text may match and the click goes elsewhere.

In an interview. Junior: cy.get always searches from the document root, even in a chain. Find searches only inside the previous element. Contains finds an element by text, and you can pass it a selector, for example a button with certain text. Middle/Senior: The search scope depends on the command type: get is a parent command, find a child one. All are queries, so they retry and re-query the DOM, and stale elements almost never occur. For list rows I take contains by the row text and then find by data-cy, so the test does not depend on order.

Which selectors does Cypress recommend and why?

Cypress recommends dedicated test attributes: data-cy, data-test or data-testid. Classes, tags and position serve markup and styles and change without regard for tests, while a test attribute exists only for them and changes deliberately. For semantic lookups there is cy.contains, when the text itself is the requirement. If the code cannot be changed, contains with a selector, a role or a stable id are the fallback.

Cypress · Locators and DOM

A designer renamed a button class and half the suite fell over. Which selectors survive that?

A test like cy.get('.btn.btn-primary.mt-2') passes until the markup changes. After a style refactoring it fails although the behaviour is the same. Tests need a selector that changes only when the thing under test changes.

How it works and why. The Cypress docs (Best Practices, “Selecting Elements”) recommend dedicated data-* attributes: data-cy, data-test or data-testid. The reason is simple: classes, tags and positions serve markup and styles, have many owners and are changed without a thought for tests. A test attribute exists only for tests, so changing it is deliberate and visible in code review. Cypress's selector picker also suggests such attributes first by default (data-cy, data-test, data-testid, data-qa). For semantic lookups there is cy.contains, and since Cypress 16.2 there is also a built-in query cy.getByRole('button', { name: 'Sign in' }); earlier the Testing Library plugin (findByRole) was used for this.

Selector resilience

data-cy, data-test, data-testida separate contract for testsgetByRole, contains + selectorchange together with the requirementid, style classesdepend on a developer and CSSnth-child, div > div > abreak on any layout change
Figure 1. The higher, the fewer reasons for a selector to break without a behaviour change.
Brittle

Classes and position

.btn.btn-primary.mt-2 and form > div:nth-child(3) > button break on a style tweak or a new field.

Stable

data-cy

[data-cy=submit] depends on neither styles, text nor DOM position.

Example: from brittle to stable.

// before: depends on styles and order
cy.get('form > div:nth-child(3) > button').click();

// after: a developer added the attribute, the test uses it
cy.get('[data-cy=submit]').click();

// text is the requirement: contains with a selector
cy.contains('button', 'Sign in').click();

// role and accessible name (Cypress 16.2+)
cy.getByRole('button', { name: 'Sign in' }).click();

Role and accessible name have an extra benefit: the test also checks that the button is reachable for a screen reader. But a copywriter can change a button text, while data-cy stays.

Limits and alternatives. If the code base cannot be changed (someone else's site, a third-party widget), you have to use contains, a role or a stable id. The attribute priority Cypress suggests is changed with Cypress.ElementSelector.defaults({ selectorPriority: ['data-cy', 'data-test'] }) (before Cypress 15 this API was called Cypress.SelectorPlayground). XPath is not built into Cypress, so it is not a default option.

And in Playwright:

Semantic locators have long been built in: getByRole, getByLabel, getByPlaceholder, getByTestId. The attribute for getByTestId is set with testIdAttribute, for example to data-cy.

Common mistakes.

  • Generated CSS-module classes (.css-1x2y3): they change with every build.
  • A data-cy that describes looks (blue-button) instead of purpose (submit): the name lies after a redesign.
  • A positional selector where order is not a requirement: the test fails from a new form field.

Check yourself

Why is data-cy more stable than the .btn-primary class?

Answer

A class belongs to styling and changes with the design. A test attribute exists only for tests, so it changes deliberately, not as a side effect.

When is cy.contains a better choice than data-cy?

Answer

When the text itself is the requirement (a message, a button name) or the page code cannot be changed. Even then add a selector: cy.contains('button', ...).

In an interview. Junior: The best are dedicated test attributes like data-cy: nobody touches them when styles change. Contains by text fits when the text is itself the requirement. Classes and positional selectors break on any markup change. Middle/Senior: A selector should change only together with what is tested. So: data-cy as a contract with developers, getByRole where accessibility matters, contains with a selector for text that is a requirement. If the code cannot be changed, that is a conscious trade-off I document in the test.

How do you narrow the search: within, eq, first, filter?

Narrowing commands: within limits the search scope, eq, first and last take an element by index, filter keeps the matching ones by selector or function. An index expresses order, which is rarely a requirement, so a row is better found by content: cy.contains by order number, then within or find. Inside within, elements outside the subject cannot be found, such as a portal at the end of body.

Cypress · Locators and DOM

A table has ten rows with a Cancel button. How do you press the right one without depending on order?

The same button repeats in every row. cy.get('[data-cy=cancel]').click() picks several elements and cannot tell which one. This is where narrowing commands come in: within, eq, first, last, filter.

How it works and why. .within(() => {...}) runs the nested commands inside the subject: there cy.get and cy.contains search only within it. within passes the subject on unchanged. .eq(n) takes an element by index (zero-based, a negative one counts from the end), .first() and .last() are shortcuts. .filter() keeps the elements of a set that match a selector or a function (the jQuery :contains() selector works too). eq, first, last and filter are queries, so they re-run together with the preceding queries of the chain; within is a regular command and does not retry. Narrowing by content beats an index, because an index expresses an order that is rarely a requirement.

From the row to the action

1. The row by textcy.contains('[data-cy=row]', text)2. Scope: within or findall commands inside the row3. Action and assertionstatus, cancel
Figure 1. The container is found by content, then everything works within its bounds.

Example: the button in the right row.

Brittle

eq(3)

After a sort or a new order a different row sits in fourth place and the test cancels someone else's order.

Stable

contains + within

The row is found by the order number, so order does not matter.

cy.contains('[data-cy=row]', 'Order #1042').within(() => {
  cy.get('[data-cy=status]').should('have.text', 'Shipped');
  cy.get('[data-cy=cancel]').click();
});

// order is the requirement: the newest is first
cy.get('[data-cy=row]').first().should('contain', '#1043');

// filter a set by content
cy.get('[data-cy=product]').filter(':contains("Flask")').first().click();

In the first block cy.get('[data-cy=status]') searches only in the found row, so other rows' statuses do not get into the assertion. The second block uses an index where it is part of the check.

Limits and alternatives. Inside within you cannot find an element that sits outside the subject in the DOM: a dropdown list or a modal rendered at the end of body. Then leave the block and search from the root. For going up there are .closest() and .parent(), for excluding .not(). Before eq it helps to make sure the list is complete: .should('have.length', 10).

And in Playwright:

Instead of within there is locator composition, instead of filter(':contains') the filter({ hasText }) option.

const row = page.getByTestId('row').filter({ hasText: '#1042' });
await row.getByTestId('cancel').click();

Common mistakes.

  • .eq(0) on a list that is still loading: the first element is found, just not the right one. Wait for the state with an assertion first.
  • An action with a side effect inside within with no assertion: after the click the block may disappear and later commands fail.
  • Expecting a new subject from within: it returns the same element it received.

Check yourself

Why is .eq(3) worse than cy.contains(row, text) for a button in a row?

Answer

An index depends on row order, which sorting, pagination and new data change. A content lookup is tied to what the test really checks.

What will not work in within for a list that opens in a portal at the end of body?

Answer

cy.get inside within searches only within the subject, and the portal lies outside it. The search must run outside the block.

In an interview. Junior: Within limits the search to one block: I find the row by text and all commands inside search only there. Eq, first and last take by index, but I use them only when the order really matters. Middle/Senior: An index encodes order, and order is rarely a requirement, so I narrow by content: contains by the number, then within or find. I keep an index for checking the order itself, such as “newest on top”. I also know the limit of within: portals and modals sit outside the block.

Why is { force: true } dangerous?

{ force: true } skips actionability checks (visibility, covering, disabled) and fires the event at the element, bypassing the point on the screen. So a test passes where a real user cannot press the button, and it hides a bug. The cause is fixed first: remove the obstacle or wait for the state with an assertion. Force is rarely justified, for example for a native input hidden by design, and always with a comment.

Cypress · Locators and DOM

The click fails, force: true was added and the test is green. Did you fix the test or hide a bug?

A cookie banner covers the button, and cy.get(...).click() fails saying the element is covered by another one. The fastest “cure” is { force: true }: the test passes. Only a user on that page still cannot press the button.

How it works and why. Before click, type, check and other actions Cypress runs actionability: it scrolls the element into view and checks that it is visible, not disabled, not readonly, not covered, not animating and not detached from the DOM. All of this models a real user action. According to the docs, { force: true } “skips the checks and always fires the event at the desired element”: Cypress does not scroll, does not check visibility, covering, disabled and so on, and does not fire the event at a descendant. A real click goes to a point on the screen, while force bypasses the screen, so a covered element receives an event the user could not cause.

What force skips

Without forceexists, visible, not covered, enabledforce: truethe event goes straight to the element
Figure 1. Force removes exactly the protection the checks exist for.
Hides a bug

click({ force: true })

A banner covers the button, the test is green, the user is stuck. The test no longer checks what it should.

Checks

Remove the obstacle first

Close the banner or wait until it disappears, then click without force. If the banner cannot be closed, that is a bug.

Reading the error: a click on a covered button

1CypressError: Timed out retrying after 4000ms: cy.click() failed because this element:

<button data-cy="buy">Buy</button>

2is being covered by another element:

<div data-cy="cookie-banner">...</div>

3Fix this problem, or use {force: true} to disable error checking.
  1. What: for four seconds Cypress kept retrying the checks before the click, and the button never became clickable.
  2. Why: another element sits at the click point, here a cookie banner. The first element in the message is the target, the second one is what covers it.
  3. Hint: Cypress mentions force, but that only switches the check off. The covering does not go away.

What to do

Close the banner and wait until it is gone: cy.get('[data-cy=cookie-banner]').should('not.exist'), then click without force. If the banner cannot be closed, that is a product bug.

Figure 2. The real error text (shortened): the numbers lead to the explanations.

Example: what to do instead of force.

// before: the test is green, the user cannot click
cy.get('[data-cy=buy]').click({ force: true });

// after: remove the real cause
cy.get('[data-cy=cookie-accept]').click();
cy.get('[data-cy=cookie-banner]').should('not.exist');
cy.get('[data-cy=buy]').should('be.enabled').click();

// justified, with a reason: the native input is hidden,
// a custom checkbox covers it
cy.get('input[type=checkbox]').check({ force: true });

The block with two assertions does not just wait: it describes the expected page state. Without force the test fails if the banner really cannot be closed, and that is a finding. For a hidden native input first try clicking its label or the custom element, as a user would.

Limits and alternatives. Justified cases are rare: native inputs hidden by design, elements that by design appear only on hover when hover cannot be reproduced. Before force try scrollIntoView, an assertion be.visible or be.enabled, the scrollBehavior setting, and for animations check waitForAnimations and animationDistanceThreshold. Next to every force leave a comment with the reason.

And in Playwright:

There is a similar { force: true } with the same risks, although per the docs it turns off only the “non-essential” actionability checks.

Common mistakes.

  • Adding force without finding the cause: the covering bug stays in the product and the suite cannot see it.
  • Putting force into a shared command (cy.clickForce): the hidden risk gets into every test.
  • Treating flakiness with force: flakiness is usually about animation or async loading, not about the checks.

Check yourself

A test with click({ force: true }) is green, yet users complain the button cannot be pressed. Why did the test not see it?

Answer

Force skips the visibility and covering checks and fires the event straight at the element, bypassing the point on the screen. A user presses what is on top, so the test and the user no longer perform the same action.

What do you do about a banner covering the button instead of force?

Answer

Close it with user actions and assert should('not.exist') or wait until it disappears, then click without force. If it cannot be closed, that is a product bug.

In an interview. Junior: Force turns off the checks: whether the element is visible, not covered, enabled. If a test passes only with force, it most likely hides a real bug. Middle/Senior: Force fires the event straight at the element while a user clicks a point on the screen, so the test stops modelling the user. I remove the cause first: close the obstacle, wait for the state with an assertion. I use force only for hidden native inputs, always with a comment.

How do you work with iframes, new tabs, and file downloads and uploads?

Cypress works in one tab, so each of the four scenarios has its own approach. The content of a same-origin iframe is reached through contentDocument.body wrapped in cy.wrap, while an iframe from another origin is blocked by the same-origin policy. New tabs are not opened: the target attribute is removed or href is checked. Uploads use .selectFile(), and a downloaded file is checked with cy.readFile.

Cypress · Locators and DOM

A payment form sits in an iframe and a link opens in a new tab. How do you test that in Cypress?

Four scenarios raise the most questions: iframes, new tabs, uploads and downloads. Cypress works in one browser tab and by default has no dedicated iframe command, so each scenario has its own approach and its own limits.

How it works and why. The test runs in the same browser as the app, but in one tab. An iframe is a separate document: cy.get('iframe') finds the element itself, and its content is reachable through contentDocument.body, which is wrapped in cy.wrap; the cypress-iframe plugin adds convenience. A cross-origin iframe is blocked by the same-origin policy; in Chromium browsers this can be relaxed with chromeWebSecurity: false, in Firefox it cannot, and cy.origin does not cover iframes. New tabs are not opened by Cypress itself: remove target from the link or check href (a real second tab needs the official @cypress/puppeteer plugin). Upload is the built-in .selectFile() command. A download is stored by the browser in the downloadsFolder (by default cypress/downloads), where you check the file with cy.readFile, which retries until the file appears.

What to use for each scenario

iframeits + cy.wrap; cross-origin is limitedNew tabremove target or check hrefUpload.selectFile()Downloadcy.readFile in downloadsFolder
Figure 1. Each scenario has its own approach, and none needs a second tab.
Possible

Same origin

An iframe from the same origin opens through contentDocument.body and cy.wrap.

Limited

Another origin

Third-party payment widgets are not directly reachable; test the integration (request, redirect), not their form.

Example: four scenarios in one file.

// iframe of the same origin
cy.get('iframe#payment')
  .its('0.contentDocument.body').should('not.be.empty')
  .then(cy.wrap)
  .find('[data-cy=card]').type('4242424242424242');

// new tab: open it in the same one
cy.get('[data-cy=docs-link]').invoke('removeAttr', 'target').click();

// or only check the requirement on the link
cy.get('[data-cy=docs-link]')
  .should('have.attr', 'target', '_blank')
  .and('have.attr', 'href', '/docs');
// upload: a path, an alias or a Buffer
cy.get('input[type=file]').selectFile('cypress/fixtures/avatar.png');
cy.get('[data-cy=dropzone]').selectFile('cypress/fixtures/avatar.png', {
  action: 'drag-drop',
});

// download: readFile retries until the file appears
cy.get('[data-cy=export]').click();
cy.readFile('cypress/downloads/report.csv').should('contain', 'Total');

.selectFile() by default needs a visible element: for a hidden input add { force: true }, which is one of the justified cases. Before a download delete the old file or use a unique name, otherwise the assertion passes on a leftover from a previous run.

Limits and alternatives. To verify that a link opens a tab, stub window.open: cy.window().then((win) => cy.stub(win, 'open').as('open')) and then cy.get('@open').should('be.calledWith', ...). If the app opens a tab and its content must be checked, the official @cypress/puppeteer plugin gives access to it through cy.puppeteer() (Chromium-family browsers only). For scenarios where tabs, third-party iframes or several users in different windows are the core of the test, Cypress is not the best tool.

And in Playwright:

Playwright is clearly stronger here: iframes via page.frameLocator(), including cross-origin ones, a new tab via context.waitForEvent('page'), upload via setInputFiles(), download via page.waitForEvent('download').

Common mistakes.

  • Taking cy.get('iframe') and calling .find at once: that is the iframe element, not its document.
  • Not waiting for the iframe to load: contentDocument.body is empty until the document loads, hence the not.be.empty assertion.
  • Looking for the downloaded file in another folder or without cleanup: the test depends on previous runs.

Check yourself

Why does the iframe example contain .should('not.be.empty')?

Answer

Until the iframe loads, its body is empty and find would find nothing. The assertion retries until the document appears, so the test waits for a ready iframe.

How do you verify that a button opens a new tab when Cypress has only one?

Answer

Stub window.open and check the call, or check the target and href attributes of the link. Cypress will not open the tab itself.

In an interview. Junior: For an iframe I take contentDocument body and wrap it in cy.wrap, but a cross-origin iframe is not reachable. Cypress itself does not open new tabs, so I remove target or check href. For upload there is selectFile, and I check a downloaded file with readFile. Middle/Senior: All four follow from the test living in one tab. For third-party iframes I test the integration, not their form, replace the tab with a window.open stub, and check a file with readFile and a unique name. If tabs and third-party iframes are the core of the test, I would take Playwright.

Selectors and data-cy

data-cy works as a contract between development and tests: the name describes purpose, with one prefix per project. The attribute is added by the author of the component, and selectors go through one command such as getBySel, so the format changes in one place. The attributes stay in production HTML, so if a build strips them, e2e on that build breaks.

Cypress · Locators and DOM

Where in a project do you agree on data-cy so that selectors do not drift between tests?

Choosing data-cy is half of the job. The other half: who adds it, how it is named and where a test gets its selector. Without that, half a year later some tests look for [data-cy=submit], others for [data-test=submit-btn], and developers remove the “unused” attributes.

How it works and why. A test attribute works as a contract between development and tests. According to the docs it does not depend on styles, text or position, and its presence in the code signals that the element is used by tests. The contract rests on three agreements: the name describes purpose (submit, order-price), not looks; one prefix per project; the attribute is added by whoever writes the component, not only by the test author. It also pays to move the selector into one command so the format changes in one place.

Drifted

Three formats

[data-cy=submit], [data-test=submit-btn], .submit: the same button, different selectors in different files.

Unified

One prefix and a helper

All selectors through one command, names by purpose, the format changes in one place.

Example: a getBySel command.

// cypress/support/commands.ts
Cypress.Commands.add('getBySel', (sel: string) => {
  return cy.get('[data-cy=' + sel + ']');
});

declare global {
  namespace Cypress {
    interface Chainable {
      getBySel(sel: string): Chainable<JQuery<HTMLElement>>;
    }
  }
}
export {};

// in a test
cy.getBySel('submit').click();
cy.getBySel('order-price').should('have.text', '$1,200');

Now renaming the attribute, for example to data-testid, is a single edit. Such a command does not change the scope rules: it is the same cy.get, so a nested lookup in a chain still needs find.

Limits and alternatives. Test attributes end up in production HTML. The volume is small and most teams keep them, but some strip them at build time. Whoever strips them must know that e2e on a production build breaks afterwards. An attribute does not replace accessibility: for elements with a role and a name getByRole (Cypress 16.2+) or cy.contains with a selector fits. Dynamic identifiers (row-1042) are better built from data, not from an index.

And in Playwright:

No helper is needed: getByTestId is built in and the attribute name is set once through testIdAttribute in the config.

Common mistakes.

  • Agreeing on the attribute only in the test author's head: a developer removes the “unused” one and the test fails.
  • A name by state or colour (red-btn): the name lies after a change.
  • One command that adds both force and the lookup: a hidden risk in every test.

Check yourself

What advantage does a getBySel command have over cy.get('[data-cy=...]') everywhere?

Answer

The selector format lives in one place: changing the attribute or naming rule does not touch a hundred tests.

Why should a data-cy name describe purpose, not looks?

Answer

Looks change with the design and the name (blue-button) starts to lie, while the purpose (submit) holds as long as the behaviour holds.

In an interview. Junior: I agree with developers on data-cy as a contract: names by purpose, one prefix, the attribute is added by the component author. Middle/Senior: I put selectors into one command such as getBySel so the format changes in one place. I know the trade-off: attributes stay in production HTML, and whoever strips them breaks e2e on a production build.