Bird
Raised Fist0
Cypresstesting~8 mins

cy.contains() for text matching in Cypress - Framework Patterns

Choose your learning style10 modes available
Framework Mode - cy.contains() for text matching
Folder Structure
    cypress/
    ├── e2e/
    │   ├── login.cy.js          # Test files using cy.contains() for text matching
    │   ├── dashboard.cy.js
    │   └── ...
    ├── fixtures/               # Static test data (JSON files)
    │   └── users.json
    ├── support/
    │   ├── commands.js         # Custom commands including cy.contains() wrappers
    │   ├── e2e.js              # Global setup for tests
    │   └── index.js
    └── cypress.config.js       # Cypress configuration file
    
Test Framework Layers
  • Test Layer (e2e/): Contains test scripts that use cy.contains() to find elements by visible text. Example: clicking buttons or verifying messages.
  • Support Layer (support/): Holds reusable commands and helpers. You can create custom commands wrapping cy.contains() for consistent text matching.
  • Fixtures Layer (fixtures/): Stores test data like user info or expected text strings used in cy.contains() assertions.
  • Configuration Layer: The cypress.config.js file sets base URLs, environment variables, and browser options.
Configuration Patterns

Use cypress.config.js to manage environments and settings:

    import { defineConfig } from 'cypress'

    export default defineConfig({
      e2e: {
        baseUrl: 'https://example.com',
        env: {
          username: 'testuser',
          password: 'password123'
        },
        setupNodeEvents(on, config) {
          // implement node event listeners here
        }
      }
    })
    

Access environment variables in tests with Cypress.env('username'). This helps when using cy.contains() to verify user-specific text.

Test Reporting and CI/CD Integration
  • Use Cypress built-in reporter for clear pass/fail results of tests using cy.contains().
  • Integrate with CI/CD pipelines (GitHub Actions, Jenkins) to run tests automatically on code changes.
  • Generate HTML or JSON reports with plugins like mochawesome for detailed test results.
  • Use screenshots and video recording on test failures to debug cy.contains() text matching issues.
Best Practices
  1. Use exact or partial text carefully: cy.contains() can match partial text by default. Use regex or exact match options to avoid false positives.
  2. Prefer semantic selectors: Combine cy.contains() with element selectors (e.g., cy.contains('button', 'Submit')) for more precise targeting.
  3. Wrap cy.contains() in custom commands: For repeated text matching patterns, create reusable commands in support/commands.js.
  4. Use fixtures for text data: Store expected text in fixture files to keep tests clean and maintainable.
  5. Handle dynamic text carefully: When text changes dynamically, use assertions with retries or wait for elements before using cy.contains().
Self Check

Where in this folder structure would you add a new custom command that wraps cy.contains() to click a button by its text?

Key Result
Organize Cypress tests with clear folder layers, use cy.contains() in tests and custom commands, manage config via cypress.config.js, and integrate reporting in CI/CD.

Practice

(1/5)
1. What does cy.contains('Submit') do in a Cypress test?
easy
A. Finds the first element containing the visible text 'Submit'.
B. Clicks the button named 'Submit' automatically.
C. Types 'Submit' into an input field.
D. Checks if the page URL contains the word 'Submit'.

Solution

  1. Step 1: Understand cy.contains() basic function

    The command searches the page for an element that has visible text matching the given string.
  2. Step 2: Analyze the given text 'Submit'

    It finds the first element that contains the text 'Submit' anywhere inside it.
  3. Final Answer:

    Finds the first element containing the visible text 'Submit'. -> Option A
  4. Quick Check:

    cy.contains('text') finds element by visible text [OK]
Hint: cy.contains() finds elements by visible text quickly [OK]
Common Mistakes:
  • Thinking cy.contains() clicks automatically
  • Confusing cy.contains() with typing commands
  • Assuming it checks URL instead of page content
2. Which of the following is the correct syntax to find a button with text 'Login' using cy.contains()?
easy
A. cy.contains(button, Login)
B. cy.contains('button', 'Login')
C. cy.contains('Login', 'button')
D. cy.contains('button' + 'Login')

Solution

  1. Step 1: Recall cy.contains() syntax with selector

    The correct syntax is cy.contains(selector, text) where selector is a string like 'button'.
  2. Step 2: Match the correct option

    cy.contains('button', 'Login') uses cy.contains('button', 'Login') which is correct. Other options misuse quotes or argument order.
  3. Final Answer:

    cy.contains('button', 'Login') -> Option B
  4. Quick Check:

    cy.contains('selector', 'text') correct syntax [OK]
Hint: Use cy.contains('selector', 'text') to narrow search [OK]
Common Mistakes:
  • Omitting quotes around selector or text
  • Swapping the order of selector and text
  • Concatenating strings incorrectly inside cy.contains()
3. What will the following Cypress code do?
cy.contains('Submit').click()
medium
A. Types 'Submit' into the focused input field.
B. Throws an error because click() cannot be chained.
C. Finds the first element with text 'Submit' and clicks it.
D. Finds all elements with 'Submit' text but does not click.

Solution

  1. Step 1: Understand cy.contains() chaining

    cy.contains('Submit') finds the first element with visible text 'Submit'.
  2. Step 2: Analyze the chained click()

    Calling .click() on the found element triggers a click event on it.
  3. Final Answer:

    Finds the first element with text 'Submit' and clicks it. -> Option C
  4. Quick Check:

    cy.contains('text').click() clicks matched element [OK]
Hint: Chain .click() after cy.contains() to click element [OK]
Common Mistakes:
  • Thinking click() types text instead
  • Assuming click() cannot be chained
  • Believing it clicks multiple elements
4. You wrote cy.contains(button, 'Save').click() but the test fails with a syntax error. What is the problem?
medium
A. You must use cy.get() before cy.contains().
B. cy.contains() cannot be chained with click().
C. The text 'Save' must be uppercase.
D. The selector button should be a string: 'button'.

Solution

  1. Step 1: Check argument types in cy.contains()

    The selector argument must be a string, so 'button' needs quotes.
  2. Step 2: Identify the syntax error cause

    Using button without quotes causes a syntax error because it's treated as a variable.
  3. Final Answer:

    The selector button should be a string: 'button'. -> Option D
  4. Quick Check:

    Selector must be string in cy.contains() [OK]
Hint: Always quote selectors in cy.contains() [OK]
Common Mistakes:
  • Forgetting quotes around selector
  • Thinking click() can't be chained
  • Assuming text case matters in cy.contains()
5. You want to verify that a page contains a link with text 'Learn More' inside a <nav> element. Which Cypress command is best?
hard
A. cy.get('nav').contains('a', 'Learn More').should('exist')
B. cy.contains('nav a', 'Learn More').click()
C. cy.contains('Learn More').should('be.visible')
D. cy.get('a').contains('nav', 'Learn More')

Solution

  1. Step 1: Narrow search inside <nav> for link text

    Use cy.get('nav') to select the nav element first.
  2. Step 2: Use contains() with selector 'a' and text 'Learn More'

    Calling .contains('a', 'Learn More') inside nav finds the link with that text.
  3. Step 3: Assert existence with should('exist')

    This confirms the link is present inside nav.
  4. Final Answer:

    cy.get('nav').contains('a', 'Learn More').should('exist') -> Option A
  5. Quick Check:

    Use get() then contains() to scope text search [OK]
Hint: Use cy.get() then contains() to scope text search [OK]
Common Mistakes:
  • Using contains() without scoping to nav
  • Trying to chain contains() incorrectly
  • Assuming contains() alone checks element existence
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard