Home  Cypress   How to inte ...

How to interact with elements in cypress

Interacting with elements in Cypress involves using its powerful API to locate elements and perform actions on them. Here’s a basic guide on how to interact with elements in Cypress:

  1. Locate Elements: Cypress allows you to select elements using jQuery-like commands. You typically use cy.get() to select elements. For example:

    // Selecting by element type and class
    cy.get('input[type="text"].search-input');
    
    // Selecting by ID
    cy.get('#username');
    
    // Selecting by data attribute
    cy.get('[data-testid="submit-button"]');
    
  2. Perform Actions: Once you've selected an element, you can perform various actions on it using Cypress commands chained to cy.get():

    • Typing Text:

      cy.get('#username').type('John Doe');
      
    • Clicking:

      cy.get('[data-testid="submit-button"]').click();
      
    • Asserting Visibility:

      cy.get('#error-message').should('be.visible');
      
    • Clearing Input:

      cy.get('#username').clear();
      
    • Selecting from Dropdown:

      cy.get('#select-country').select('Canada');
      
    • Hovering Over Element:

      cy.get('.menu-item').trigger('mouseover');
      
    • Dragging and Dropping:

      cy.get('#draggable').drag('#droppable');
      
  3. Chaining Commands: Cypress commands are chainable, allowing you to perform multiple actions sequentially. For example:

    cy.get('#username')
      .type('John Doe')
      .should('have.value', 'John Doe');
    
    cy.get('[data-testid="submit-button"]').click();
    
    cy.get('#success-message').should('be.visible');
    
  4. Assertions: Cypress emphasizes assertions to verify expected behaviors or states. You can use built-in assertions to check conditions after actions:

    cy.get('#username').should('be.visible');
    cy.get('#error-message').should('contain.text', 'Invalid username');
    
  5. Handling Wait and Timeouts: Cypress automatically waits for elements to become available or actions to complete. You can explicitly wait for an element or condition using cy.wait() or handle timeouts using cy.timeout().

Published on: Jun 28, 2024, 01:39 AM  
 

Comments

Add your comment