Bird
Raised Fist0
Cypresstesting~8 mins

cy.click() in Cypress - Framework Patterns

Choose your learning style10 modes available
Framework Mode - cy.click()
Folder Structure of a Cypress Test Project
  cypress/
  ├── e2e/                 # End-to-end test files
  │   ├── login.cy.js      # Example test file
  │   └── cart.cy.js       # Another test file
  ├── fixtures/            # Test data files (JSON, etc.)
  │   └── users.json       # Sample user data
  ├── support/             # Support files and custom commands
  │   ├── commands.js      # Custom Cypress commands
  │   └── e2e.js           # Global setup for tests
  └── videos/              # Test run videos (auto-generated)
  cypress.config.js        # Cypress configuration file
  package.json             # Project dependencies and scripts
  
Test Framework Layers in Cypress
  • Test Layer (cypress/e2e): Contains test scripts using cy.click() and other commands to simulate user actions.
  • Support Layer (cypress/support): Holds reusable code like custom commands (commands.js) and global hooks (e2e.js).
  • Fixtures Layer (cypress/fixtures): Stores test data files to keep tests clean and data-driven.
  • Configuration Layer (cypress.config.js): Defines environment settings, base URLs, browser options, and test retries.
Configuration Patterns in Cypress

Use cypress.config.js to manage settings like:

  • Base URL: Set baseUrl for easy navigation in tests.
  • Environment Variables: Use env to store credentials or flags, accessed via Cypress.env().
  • Browser Selection: Configure which browser to run tests on via CLI or config.
  • Retries and Timeouts: Adjust retries and defaultCommandTimeout for flaky tests.
  // Example cypress.config.js
  import { defineConfig } from 'cypress'

  export default defineConfig({
    e2e: {
      baseUrl: 'https://example.com',
      env: {
        username: 'testuser',
        password: 'password123'
      },
      retries: 2,
      defaultCommandTimeout: 8000
    }
  })
  
Test Reporting and CI/CD Integration
  • Built-in Reporter: Cypress provides a default interactive test runner with pass/fail results.
  • Custom Reporters: Integrate with mochawesome or junit reporters for detailed HTML or XML reports.
  • CI/CD Integration: Run Cypress tests in pipelines (GitHub Actions, Jenkins, GitLab CI) using cypress run command.
    • Save videos and screenshots on failure for debugging.
    • Publish reports as pipeline artifacts.
Best Practices for Using cy.click() in Cypress Framework
  1. Use Clear Locators: Prefer data attributes like data-cy for stable selectors instead of classes or IDs that may change.
  2. Wait for Elements: Use cy.get() with built-in retries before cy.click() to ensure the element is ready.
  3. Custom Commands: Wrap common click actions in custom commands for reuse and readability.
  4. Accessibility: Test clicks on elements accessible by keyboard and screen readers to ensure usability.
  5. Handle Dynamic UI: Use assertions or cy.wait() wisely to handle animations or loading states before clicking.
Self-Check Question

Where in this Cypress framework structure would you add a new custom command that wraps cy.click() with extra logging?

Key Result
Organize Cypress tests with clear folder layers, use stable selectors for cy.click(), and configure environments for reliable automation.

Practice

(1/5)
1. What does the cy.click() command do in Cypress testing?
easy
A. Types text into an input field
B. Selects an element by its CSS selector
C. Simulates a user clicking on a selected element
D. Waits for a specified amount of time

Solution

  1. Step 1: Understand the purpose of cy.click()

    The cy.click() command is used to simulate a user clicking on an element in the browser during a test.
  2. Step 2: Differentiate from other commands

    Typing text uses cy.type(), selecting elements uses cy.get(), and waiting uses cy.wait(). So, cy.click() specifically simulates clicks.
  3. Final Answer:

    Simulates a user clicking on a selected element -> Option C
  4. Quick Check:

    cy.click() = Simulate click [OK]
Hint: Click means simulate user click on element [OK]
Common Mistakes:
  • Confusing cy.click() with typing or selecting elements
  • Thinking cy.click() waits or pauses the test
  • Using cy.click() without selecting an element first
2. Which of the following is the correct syntax to click a button with id submitBtn using Cypress?
easy
A. cy.click().get('#submitBtn')
B. cy.click('#submitBtn')
C. cy.find('#submitBtn').click()
D. cy.get('#submitBtn').click()

Solution

  1. Step 1: Select the element before clicking

    In Cypress, you must first select the element using cy.get() with the CSS selector, then call .click() on it.
  2. Step 2: Check each option's syntax

    cy.click('#submitBtn') tries to call cy.click() with a selector, which is invalid. cy.find('#submitBtn').click() uses cy.find(), which is not a Cypress command. cy.click().get('#submitBtn') calls cy.click() before selecting, which is incorrect.
  3. Final Answer:

    cy.get('#submitBtn').click() -> Option D
  4. Quick Check:

    Select with cy.get(), then .click() [OK]
Hint: Always use cy.get(selector).click() to click elements [OK]
Common Mistakes:
  • Calling cy.click() directly with a selector
  • Using non-existent commands like cy.find()
  • Calling click() before selecting the element
3. What will happen when the following Cypress code runs?
cy.get('.btn-primary').click()

Assuming there are multiple elements with class btn-primary on the page.
medium
A. Clicks the first element with class btn-primary
B. Clicks all elements with class btn-primary
C. Throws an error because multiple elements match
D. Clicks a random element with class btn-primary

Solution

  1. Step 1: Understand cy.get() behavior with multiple matches

    cy.get() selects all matching elements, but .click() clicks only the first matched element by default.
  2. Step 2: Confirm no error is thrown

    Cypress does not throw an error when multiple elements match; it acts on the first element unless specified otherwise.
  3. Final Answer:

    Clicks the first element with class btn-primary -> Option A
  4. Quick Check:

    cy.get() + .click() clicks first match [OK]
Hint: Click acts on first matched element by default [OK]
Common Mistakes:
  • Assuming all matched elements are clicked
  • Expecting an error when multiple elements match
  • Thinking click chooses a random element
4. You wrote this Cypress test:
cy.get('.submit-btn').click()

But the test fails with error: Timed out retrying: Expected to find element: .submit-btn, but never found it.
What is the most likely cause?
medium
A. The selector .submit-btn does not match any element on the page
B. You forgot to call cy.click() after cy.get()
C. The click() command is not supported on buttons
D. The page is not loaded before running the test

Solution

  1. Step 1: Analyze the error message

    The error says Cypress could not find any element matching .submit-btn. This means the selector is incorrect or the element is missing.
  2. Step 2: Check other options

    You did call click() correctly, so B is wrong. click() works on buttons, so C is wrong. If the page was not loaded, the error would be different or you would use cy.visit() and wait commands, so A is less likely.
  3. Final Answer:

    The selector .submit-btn does not match any element on the page -> Option A
  4. Quick Check:

    Selector not found = test fails [OK]
Hint: Check if selector matches any element before clicking [OK]
Common Mistakes:
  • Assuming click() is missing when it is present
  • Thinking click() can't be used on buttons
  • Ignoring selector correctness or page load state
5. You want to click a checkbox only if it is not already checked. Which Cypress code correctly does this?
hard
A. cy.get('#agree').check()
B. cy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } })
C. cy.get('#agree').click({ force: true })
D. cy.get('#agree').click()

Solution

  1. Step 1: Understand the requirement

    You want to click the checkbox only if it is not checked yet, to avoid toggling it off accidentally.
  2. Step 2: Analyze each option

    cy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } }) uses then to check if the checkbox is unchecked, then clicks it. cy.get('#agree').click({ force: true }) forces a click regardless of state. cy.get('#agree').check() uses check(), which is a better way to check a checkbox but not a click. cy.get('#agree').click() clicks unconditionally.
  3. Step 3: Choose the best option

    cy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } }) correctly checks the state and clicks only if unchecked, matching the requirement.
  4. Final Answer:

    cy.get('#agree').then($el => { if (!$el.is(':checked')) { cy.wrap($el).click() } }) -> Option B
  5. Quick Check:

    Check state before click to avoid toggling off [OK]
Hint: Check checkbox state before clicking to avoid toggling [OK]
Common Mistakes:
  • Clicking checkbox without checking state
  • Using click({ force: true }) unnecessarily
  • Confusing click() with check()
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