0
0
Cypresstesting~15 mins

Common assertions (exist, be.visible, have.text) in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify visibility and text of a welcome message on homepage
Preconditions (1)
Step 1: Open the homepage URL 'http://localhost:3000/'
Step 2: Locate the element with id 'welcome-msg'
Step 3: Check that the element exists in the DOM
Step 4: Check that the element is visible on the page
Step 5: Check that the element's text is exactly 'Welcome to Our Site!'
✅ Expected Result: The element with id 'welcome-msg' exists, is visible, and displays the text 'Welcome to Our Site!'
Automation Requirements - Cypress
Assertions Needed:
Element exists in the DOM
Element is visible
Element has exact text 'Welcome to Our Site!'
Best Practices:
Use cy.get() with a stable selector (id)
Chain assertions for readability
Avoid using arbitrary waits; rely on Cypress automatic waits
Automated Solution
Cypress
describe('Homepage welcome message test', () => {
  it('should verify the welcome message exists, is visible, and has correct text', () => {
    cy.visit('http://localhost:3000/')
    cy.get('#welcome-msg')
      .should('exist')
      .and('be.visible')
      .and('have.text', 'Welcome to Our Site!')
  })
})

This test opens the homepage URL using cy.visit(). Then it finds the element with id welcome-msg using cy.get(). The test chains three assertions: exist to confirm the element is in the page's HTML, be.visible to confirm the user can see it, and have.text to check the exact text content. Chaining assertions improves readability and efficiency. Cypress automatically waits for elements to appear, so no manual waits are needed.

Common Mistakes - 3 Pitfalls
{'mistake': 'Using cy.get() without waiting for element to appear', 'why_bad': 'The test may fail if the element loads slowly and is not yet in the DOM.', 'correct_approach': "Rely on Cypress's built-in automatic waiting with cy.get() and assertions chained."}
Using contains() instead of get() for exact text match
{'mistake': "Checking visibility with .should('exist') only", 'why_bad': 'Element may exist but be hidden, so test misses visibility check.', 'correct_approach': "Add .should('be.visible') to confirm user can see the element."}
Bonus Challenge

Now add data-driven testing with 3 different welcome messages for different user roles

Show Hint