Search code examples
reactjshrefcypress

How to click link in Cypress?


I want to click on below link in a page with several other links like this one. I have tried cy.get() with a number of alternative ways. I also tried cy.contains('Content 6') but received an error.

<div class="column">
    <a href="/admin/contents/109">
        <div class="ui segment">
            <div class="ui center aligned header">
                Content 6
                <div class="sub header">Add description to content packages
                </div>
            </div>
        </div>
    </a>
</div>

This was my final solution:

cy.get('a[href*="admin/contents"]').contains('Content 6').click()

I found the solution on this page and with help from user called Udo: https://docs.cypress.io/faq/questions/using-cypress-faq.html#How-do-I-get-an-element’s-text-contents

The href code gives more example on how to handle this problem then other examples for same problem.


Solution

  • you have to "get" the correct element to click on. in your case it could be handled like this:

    // find the link with href attribute containing "admin/contents" and click it
    cy.get('a[href*="admin/contents"]').click()