0
0
Cypresstesting~5 mins

Common assertions (exist, be.visible, have.text) in Cypress

Choose your learning style9 modes available
Introduction

Assertions check if things on a webpage are correct. They help us know if the page works as expected.

Check if a button or link is present on the page before clicking it.
Verify that a message or label is visible to the user.
Confirm that a heading or paragraph has the right text.
Make sure an error message appears after a wrong input.
Ensure a loading spinner disappears after content loads.
Syntax
Cypress
cy.get('selector').should('exist')
cy.get('selector').should('be.visible')
cy.get('selector').should('have.text', 'expected text')

exist checks if the element is in the page's HTML.

be.visible checks if the element can be seen by the user.

Examples
Check if the submit button is present in the page.
Cypress
cy.get('#submit-button').should('exist')
Verify the welcome message is visible to the user.
Cypress
cy.get('.welcome-message').should('be.visible')
Confirm the main heading has the exact text.
Cypress
cy.get('h1').should('have.text', 'Welcome to Our Site')
Sample Program

This test visits a sample page. It checks if the banner exists, is visible, and has the heading text 'Kitchen Sink'.

Cypress
describe('Common Assertions Test', () => {
  beforeEach(() => {
    cy.visit('https://example.cypress.io')
  })

  it('checks element existence', () => {
    cy.get('.banner').should('exist')
  })

  it('checks element visibility', () => {
    cy.get('.banner').should('be.visible')
  })

  it('checks element text', () => {
    cy.get('.banner h1').should('have.text', 'Kitchen Sink')
  })
})
OutputSuccess
Important Notes

Use unique and stable selectors to avoid flaky tests.

Text assertion with have.text checks exact text including spaces.

Visibility means the element is not hidden by CSS or overlapped.

Summary

Assertions help confirm page elements are correct and visible.

Use exist to check presence, be.visible for visibility, and have.text for exact text.

These checks make tests reliable and user-focused.