Alexandru Cristian
Alexandru Cristian

Reputation: 79

What is the selector for a link in Cypress?

I have this HTML code

<li class="menu-level-1">

    <a href="/Public/app/#/calendar">
        <i class="site-menu-icon material-icons">date_range</i>
        <span>
            Calendar
        </span>

    </a>
</li>

I don't know exactly what I need to select in Cypress to automate the press of the calendar button.

I don't have a unique css or id class so I can't isolate it from the rest of the menu items. I only have what is shown above.

Upvotes: 2

Views: 98

Answers (3)

madhuri varada
madhuri varada

Reputation: 93

cy.get('li').within(() => {
cy.get('a[href="/Public/app/#/calendar"]').find('.site-menu-icon.material-icons').contains('Calendar').click()
})

cy.get('li') As per you code I directly trigger the list tag

within is used to select the sub id's or classes in the list tag

cy.get('a[href="/Public/app/#/calendar"]') This selects an (anchor) element within the

  • that has an href attribute with the value "/Public/app/#/calendar". This is likely a link to a calendar page or section.

    .find('.site-menu-icon.material-icons') This searches within the selected anchor element for a child element with both the site-menu-icon and material-icons classes. This is typically an icon within the anchor link.

    .contains('Calendar') This further narrows down the selection to elements that contain the text "Calendar". It ensures that the element you are about to interact with is labeled "Calendar".

    .click() Finally, this command clicks on the element that has been selected by the previous steps.

    Upvotes: -1

  • Seeker
    Seeker

    Reputation: 465

    I think you want to click the element <a href="/Public/app/#/calendar"> since it has the href.

    There's lots of ways to target it, the one to use depends on what is unique on the page

    cy.contains('a', 'Calendar').click()  // if the word Calendar only appears on this link
    
    cy.get('a[href="/Public/app/#/calendar"]').click()  // specifies by the link itself
    
    cy,get('i.site-menu-icon').parent().click()  // if the icon is the unique thing
    

    Upvotes: 5

    Krupal Vaghasiya
    Krupal Vaghasiya

    Reputation: 550

    You can use custom xpath like //*[text()="Calendar"]

    If you have found many others on your web page, you can give an index like //*[text()="Calendar"][1] make sure here the index always starts with 1, not 0.

    Upvotes: 0

    Related Questions