0
0
CypressHow-ToBeginner ยท 3 min read

How to Click Element in Cypress: Simple Guide

In Cypress, you click an element using the .click() command after selecting it with cy.get(). For example, cy.get('button').click() finds the button and clicks it.
๐Ÿ“

Syntax

The basic syntax to click an element in Cypress is:

  • cy.get(selector): Finds the element using a CSS selector.
  • .click(): Clicks the found element.

You can chain these commands to perform a click on the selected element.

javascript
cy.get('selector').click()
๐Ÿ’ป

Example

This example shows how to click a button with the id submit-btn. It finds the button and clicks it.

javascript
describe('Click Button Test', () => {
  it('Clicks the submit button', () => {
    cy.visit('https://example.cypress.io')
    cy.get('#submit-btn').click()
  })
})
Output
Test passes if the button is found and clicked without errors.
โš ๏ธ

Common Pitfalls

Common mistakes when clicking elements in Cypress include:

  • Using incorrect or non-unique selectors that do not find the element.
  • Trying to click elements that are not visible or disabled.
  • Not waiting for the element to appear before clicking.

Always ensure the element is visible and enabled before clicking.

javascript
/* Wrong: selector does not exist or is wrong */
cy.get('.wrong-class').click()

/* Right: use correct selector and ensure visibility */
cy.get('.correct-class').should('be.visible').click()
๐Ÿ“Š

Quick Reference

CommandDescription
cy.get('selector')Selects element(s) by CSS selector
.click()Clicks the selected element
.should('be.visible')Asserts element is visible before action
.click({ force: true })Clicks element even if not visible or disabled
โœ…

Key Takeaways

Use cy.get('selector').click() to find and click elements in Cypress.
Always verify the selector is correct and the element is visible before clicking.
Use assertions like .should('be.visible') to avoid clicking hidden elements.
Use { force: true } option cautiously to click elements that are not interactable.
Clear, unique selectors make tests more reliable and easier to maintain.