Cypress - difference between find() and within() methods

Viewed 2894

My question is simple: which differences are there between using either of these methods:
cy.get('.wtv').find('.sub-wtv');

cy.get('.wtv').within(() => {cy.get('.sub-wtv');});

From the documentation
https://docs.cypress.io/api/commands/find.html
https://docs.cypress.io/api/commands/within.html

they both let us work with a "sub DOM" in which we can do whatever we would like, like searching a specific element and assert it.
It seems to me that this may be almost as an alias of each other?!
Can someone clarify this for me? Or point me in the right direction?
Also, performance wise, is one of them better than the other? I do understand that they may have different implementations, but the input and output aren't the same for both?

1 Answers

.find() is used for single search of an element, but only limits your actions to that element

.within() lets you to change the scope of searching the sub elements and call them directly with cy.get('subelementSelector'), and also work with them. The down side is, you can`t call elements from outside the scope of the parent element.

The third way is then. cy.get('elementSelector').then(element=>{//some code}) - this allows you to pass the element to a function for usage. You can search sub elements within with cy.get(element).find('subelementSelector'). Also you can use the usual commands for elements located outside the parent element scope. This has longer sintax, but greater scope.

Edit: To clarify .find() - allows a single usage of an element .within(passedFunction()=>{}) - changes the scope for DOM elements of the passedFunction to just child elements .then(element=>{}) - doesn't change the scope, but creates a JQ variable of the variable, that is available to use in the then function cy.get('parentSelector childSelector') - is the css way of getting the same result as .find()

Related