Warm tip: This article is reproduced from stackoverflow.com, please click
cypress javascript

Is it better to use 'contains' or 'get' to find an element?

发布于 2020-04-20 11:04:30

I'm writing a login.spec.js, and at this point, I'm checking the availability of further login options links (I still didn't have the chance to create a specific label to test these elements, as Best Practices suggest):

<span id="DDB_Social_List">
    <span>Further login options:</span>
    <a href="..."><span><label class="icon soclgn facebook"></label><strong>Facebook</strong></span></a>
    <a href="..."><span><label class="icon soclgn paypal"></label><strong>Paypal</strong></span></a>
    <a href="..."><span><label class="icon soclgn microsoft"></label><strong>Windows Live</strong></span></a>
</span>

I implemented two different ways of checking the availability of these links:

cy.get('span#DDB_Social_List > a:nth-child(2)').should('have.attr', 'href','...')

and

cy.contains('Facebook').should('have.attr', '...')

Which way is better and why? I have completely no idea.

Questioner
Noob_Number_1
Viewed
64
DurkoMatko 2020-02-05 22:26

I'd suggest to use .get() if you know what the appropriate selector for your element is. If you'd use a simple .contains('Facebook') and there is another element which contains the word Facebook, you're risking cypress will match that element. I guess if several elements match, it depends on the order in the DOM tree. In such case, you'd need to be sure about the order of the elements and use .first() or .last() commands (https://docs.cypress.io/api/commands/first.html)

Using .get() is conditioned by you knowing the selector(tag, class, attributes etc). It's more decisive and selects the exact element you specify with the selector. Use get and avoid the risk of matching another element with the same text.

You can read more on the usage of those two here:

In your particular case, if there was a div above your list (e.g. <div> Facebook is amazing!</div>) cy.contains('facebook') would match it and the attribute you're looking for would probably be different and therefore would your test fail.