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:
-
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"]');
-
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');
-
-
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');
-
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');
-
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 usingcy.timeout()
.