elijahcarrel
elijahcarrel

Reputation: 4117

Cypress: any difference between cy.get("a").find("b") and cy.get("a b")

It seems like they're identical. Is there ever any difference in output between cy.get("a").find("b") and cy.get("a b")?

(Where a and b are some selectors, e.g. div and span, or .someClass and .someOtherClass.)

Upvotes: 26

Views: 32787

Answers (5)

Rafael Fraga Walter
Rafael Fraga Walter

Reputation: 335

I switched to using cy.get("a").find("b").

Even though both yield the same result, this "two element" option is easier to mantain. It is faster identify which element is missing if the test breaks.

Upvotes: 0

Lir Segev
Lir Segev

Reputation: 21

There is no difference in the result, usually.

cy.get("a").find("b").click() will only retry find('b').click(), while cy.get("a b").click() will retry the whole selection cy.get("a b"). https://docs.cypress.io/guides/core-concepts/retry-ability#Only-the-last-command-is-retried

Usually both will get you the same result but when the result is different it is annoying to debug. I try and stick to one command as much as I can.

Upvotes: 2

Aneesh Narayanan
Aneesh Narayanan

Reputation: 31

find() wont work on the cy rather it can work on a chained DOM. the below command would throw error cy.find('.progress') // Errors, cannot be chained off 'cy'

Upvotes: 3

RezKesh
RezKesh

Reputation: 2942

As you stated in your question there is not difference between cy.get("a").find("b") and cy.get("a b"). But the most important difference between find and get commands in Cypress is that cy.get() is chained off of cy, it always looks for the selector within the entire document as stated in Cypress documents. But as again stated in Cypress documents find works as follows:

Get the descendent DOM elements of a specific selector.

So the command cy.get("a").find("b") returns all the b elements which are successor of an a element, but cy.get("a").get("b") finds all the a and b elements regardless of they are parent and child.

Upvotes: 42

Joshua Wade
Joshua Wade

Reputation: 5293

There is no difference in result, but there is a difference in implementation.

From the docs for the .find() command:

The querying behavior of this command matches exactly how .find() works in jQuery.

In other words,

cy.get("a").find("b");

is equivalent to the following JQuery:

$("a").find("b");

$("a").find("b"); will produce the same result as $("a b"), but will use a different method to get there.


I've done a bit of testing to confirm this on a fairly complex page:

testing result

Notice how the number results is the same for cy.get("td").find("tr") and cy.get("td tr").

Upvotes: 14

Related Questions