0
0
Cypresstesting~15 mins

cy.contains() for text matching in Cypress - Build an Automation Script

Choose your learning style9 modes available
Verify presence of specific text on the homepage using cy.contains()
Preconditions (2)
Step 1: Open the homepage URL in the browser
Step 2: Use cy.contains() to find the text 'Welcome to Our Site'
Step 3: Verify that the text is visible on the page
✅ Expected Result: The text 'Welcome to Our Site' is found and visible on the homepage
Automation Requirements - Cypress
Assertions Needed:
Verify that cy.contains('Welcome to Our Site') finds the element
Assert that the element containing the text is visible
Best Practices:
Use cy.contains() with exact text for clarity
Chain .should('be.visible') for assertion
Avoid using overly broad selectors
Use beforeEach hook to visit the page before each test
Automated Solution
Cypress
describe('Homepage Text Verification', () => {
  beforeEach(() => {
    cy.visit('https://example.com')
  })

  it('should find and display the welcome text', () => {
    cy.contains('Welcome to Our Site').should('be.visible')
  })
})

The describe block groups the test related to homepage text verification.

The beforeEach hook ensures the homepage is loaded before each test, keeping tests independent and clean.

The test uses cy.contains('Welcome to Our Site') to find the element with the exact text.

Chaining .should('be.visible') asserts that the text is actually visible to the user, confirming the page loaded correctly.

Common Mistakes - 3 Pitfalls
Using cy.contains() with partial or incorrect text
{'mistake': 'Not asserting visibility after cy.contains()', 'why_bad': 'Finding the element alone does not guarantee it is visible to the user.', 'correct_approach': "Always chain .should('be.visible') to confirm the element is displayed."}
Visiting the page inside the test instead of beforeEach
Bonus Challenge

Now add data-driven testing to verify multiple texts like 'Welcome to Our Site', 'Contact Us', and 'About Us' are visible on the homepage.

Show Hint