Querying HTML elements in Cypress primarily relies on the cy.get() method, which allows you to query elements on the page using various selectors. Here are some examples of querying HTML tags using the cy.get() method:
Querying by Tag Name
If you want to select all <button> elements, you can query them as follows:
javascriptcy.get('button');
Using Class Selectors
Assuming you have an element like <div class="profile"> in your HTML, you can query this div using a class selector:
javascriptcy.get('.profile');
Using ID Selectors
If your element has an ID, such as <input id="username">, you can query it using an ID selector:
javascriptcy.get('#username');
Using Attribute Selectors
For elements with specific attributes, such as <input type="email">, you can use attribute selectors:
javascriptcy.get('input[type="email"]');
Using Combinator Selectors
You can combine multiple conditions for precise querying, for example, for <form id="loginForm" class="active">, you can query it as:
javascriptcy.get('form#loginForm.active');
Using Child and Descendant Element Selectors
If you want to select a specific child or descendant element, you can do the following:
javascript// Select direct child <li> elements under <ul> cy.get('ul > li'); // Select all <p> descendant elements within <div> cy.get('div p');
Using the :contains() Pseudo-class Selector
To select elements containing specific text, you can use the :contains() selector:
javascriptcy.get('button:contains("Submit")');
Using .within() to Query Child Elements
When you need to query elements within a specific parent element, you can use the .within() method to restrict the query scope and improve accuracy.
javascriptcy.get('#navbar').within(() => { cy.get('.nav-links'); // Only queries '.nav-links' within the element with id 'navbar' });
Using .find() to Query Descendant Elements
The .find() method is used to search for descendant elements within a selected jQuery object set:
javascriptcy.get('.container').find('section');
Using Aliases
If you need to query the same element multiple times, using aliases can be convenient. First, assign an alias to the element using the .as() method:
javascriptcy.get('button').as('submitButton');
Then, you can reference this alias using the @ symbol:
javascriptcy.get('@submitButton').click();
Combining with Assertions for Querying
Cypress enables you to combine assertions with queries to verify that elements possess certain states or attribute values:
javascript// Verify that the element exists and is visible cy.get('.important-message').should('be.visible'); // Verify the value of an input field cy.get('input[name="email"]').should('have.value', 'user@example.com');
In real-world Cypress tests, choosing the appropriate query methods and selectors is essential for accurately locating elements and crafting reliable tests.