0
0
CypressHow-ToBeginner ยท 3 min read

How to Assert Element Exists in Cypress: Simple Guide

In Cypress, to assert that an element exists, use cy.get(selector).should('exist'). This command waits for the element matching the selector to appear and passes if found, otherwise it fails the test.
๐Ÿ“

Syntax

The basic syntax to assert an element exists in Cypress is:

  • cy.get(selector): Finds the element(s) matching the CSS selector.
  • .should('exist'): Asserts that the element is present in the DOM.
javascript
cy.get('selector').should('exist')
๐Ÿ’ป

Example

This example shows how to check if a button with the class .submit-btn exists on the page.

javascript
describe('Element existence test', () => {
  it('checks if submit button exists', () => {
    cy.visit('https://example.cypress.io')
    cy.get('.submit-btn').should('exist')
  })
})
Output
Test passes if the element with class '.submit-btn' is found; fails if not.
โš ๏ธ

Common Pitfalls

Common mistakes when asserting element existence include:

  • Using cy.get() with a wrong or too specific selector that never matches any element.
  • Expecting cy.get() to check visibility; it only checks presence in the DOM.
  • Not waiting for asynchronous content to load before asserting.

Remember, cy.get() retries automatically until timeout, but if the selector is wrong, the test will fail.

javascript
/* Wrong: selector does not exist, test fails */
cy.get('.non-existent-class').should('exist')

/* Right: correct selector */
cy.get('.submit-btn').should('exist')
๐Ÿ“Š

Quick Reference

CommandDescription
cy.get('selector')Finds element(s) matching the selector
should('exist')Asserts element is present in the DOM
should('be.visible')Asserts element is visible (different from exist)
cy.contains('text')Finds element containing specific text
โœ…

Key Takeaways

Use cy.get(selector).should('exist') to assert element presence in Cypress.
cy.get retries automatically until the element appears or timeout.
Ensure your selector matches the element you want to check.
Existence means the element is in the DOM, not necessarily visible.
Use should('be.visible') if you want to check visibility instead.