How to check if an element is clickable in Cypress

Last updated on Mar 5, 2023 by Suraj Sharma



In this tutorial, you will learn how you can check if an element is clickable in Cypress.


First, we will use the .should('be.visible') method to check if an element is visible on the page, which is a good indicator that it is clickable. Then, we will use the .should('be.enabled') command to check if an element is enabled, which means it can receive click events.

Here's an example of how to check if an element is clickable in Cypress:


  cy.get('.btn')
  .should('be.visible')
  .should('be.enabled')
  .click(); // click the element if it is clickable


In this example, we're selecting an element with the class name .btn and chaining the .should('be.visible') and .should('be.enabled') methods to check if it is clickable. If the element is clickable, we're then using the .click() method to trigger a click event on it.


We can also use the .should('have.attr', 'href') command to check if an element has a href attribute, which is a common attribute of clickable elements such as links and buttons.

Here's an example to use .should() method in Cypress:


  cy.get('.my-link')
    .should('have.attr', 'href')
    .and('include', 'example.com'); // check that the href includes a specific URL


In this example, we're selecting a link element with the class name .my-link and using the .should('have.attr', 'href') command to check if it has a href attribute. We're then using the .and('include', 'example.com') command to check that the href attribute includes the URL "example.com".



Related Solutions


Rate this post


Suraj Sharma is a Full Stack Software Engineer. He holds a B.Tech degree in Computer Science & Engineering from NIT Rourkela.