Learner
Learner

Reputation: 53

In cypress testing how to use value of a selector partially?

So I have these selectors:

cy.get(':nth-child(1) > abc-51 > xyz')
cy.get(':nth-child(2) > abc-51 > xyz')
cy.get(':nth-child(3) > abc-51 > xyz')

How do I only use cy.get(':nth-child(1)') or cy.get(':nth-child(2)') instead of whole thing because the issue is abc-51 keeps changing like it will become abc-43, etc. so tests keeps on failing.

Upvotes: 1

Views: 791

Answers (2)

TesterDick
TesterDick

Reputation: 10550

Each section of the selector is a different element level, and having > between them means "parent-child" relationship.

But if you omit > and just use a space between selectors, it should still work as you now have "parent-grandchild" (in your case), or generally a "parent-descendent" relationship.

So, just use this as your partial selector:

cy.get(':nth-child(1) xyz')

Here is another question for reference:
What is the difference direct descendent (>) vs. descendant in jQuery selectors?


Note you can also use Cypress .find() to do a descendent search:

cy.get(':nth-child(1)').find('xyz')

Upvotes: 1

agoff
agoff

Reputation: 7165

Adding ^ in your selector will match on selectors that begin with that value. In your example, the following should work:

cy.get(':nth-child(1) > [whatever-attribute^="abc-"] > xyz');

Upvotes: 2

Related Questions