Wanna get rid of snoring? Have sex every day

There is a common belief among people that sex helps to stop snoring. There is no direct scientific evidence for that. However, several sleeping medicine producers conducted surveys among people who…

Smartphone

独家优惠奖金 100% 高达 1 BTC + 180 免费旋转




How To Find HTML Elements Using Cypress Locators

Since Cypress is an open-source framework suited for testing modern web applications, many QA engineers prefer Cypress test automation over testing with other automation frameworks.

Akin to locators in Selenium, Cypress locators are also used to find WebElements in the HTML Document Object Model (DOM). Once you find multiple elements in Cypress, relevant operations can be performed on these elements or assert their presence for validation.

Locators are generally classified in the following categories, while they are being used to find multiple elements in Cypress:

Cypress supports only CSS selectors out of the box for locating elements in the DOM. So in case you intend to use other web locators like XPath, ID, etc., with Cypress, you need to add relevant external packages that support using those with Cypress locators.

IDs are the unique attributes given to the HTML elements that can be identified and updated with minimal effort. The ID attribute is unique across the DOM, due to which it is the fastest way for locating the required WebElement. It also helps in accelerating the interactions with the underlying elements in the DOM.

Here is a sample HTML page that showcases the syntax of ID in HTML:

Here, <ul> tag can be identified uniquely with CSS selectors command using $(‘#lists’).

Demonstration: ID locator in Cypress

Let’s look at using an ID locator in Cypress using the example site that we showed earlier. Here, we locate the search bar on the site; the HTML representation of the search bar is below:

Here is the implementation that demonstrates the use of the ID locator in Cypress:

cy.get() is used in Cypress to find multiple elements in DOM. The method accepts a parameter in the form of an identifier. Here we pass the ID of the element with ‘#’ as a prefix. Since the call is chainable, we used type() to enter values and used should() to assert the visibility of the corresponding WebElement.

Shown below is the execution screenshot, which indicates that the test execution was successful:

Here is a sample HTML page that showcases the syntax of NAME in HTML:

Demonstration: NAME locator in Cypress

Shown below is the syntax of the NAME locator in Cypress:

where <tag> can be HTML tags like input, form, etc. <tag> is optional, when not specified, it will match name against all the tags (wherever match is found).

Code walkthrough

The Inspect tool in Google Chrome is used for locating the element using the CSS Selector. Here is how we use the browser console using $() as the CSS selector:

Once the search results are available, we can use the ID locator in Cypress to find multiple elements and assert using Cypress’s built-in assertion method should(‘be.visible’). An assert is raised if the search results are not displayed properly.

Execution

Shown below is the execution snapshot, which indicates the respective WebElement was located successfully using the NAME locator:

Attributes are ways to set a particular property of the HTML element. They also help define the behavior of the elements when a specific condition is set and triggered. Attributes are applied to almost all the HTML tags and work similarly to the NAME locator in Cypress. Thus, we can use the same syntax for locating elements using other attributes as well.

Shown below is the syntax to use attributes in Cypress:

Additionally, consider a case where one would like to use Cypress to find multiple elements or all of them having attribute titles whose value contains ‘store’ (e.g., store-1, store-2, …). One of the brute force ways is to find each element one by one with the exact attribute value using the above syntax. However, this task is mundane and not beneficial when we need to find multiple elements in Cypress and add some common functional logic to them.

A better approach would be to use the regex-supported syntax in the CSS selector to get the list of items in one go.

Fortunately, Cypress provides an easier way to tackle this problem, where you can use patterns like starts-with and ends-with particular substring to match all the elements in the DOM.

Demonstration : Using Attributes in Cypress

Code Walkthrough

Step1

The cy.get() method is used in Cypress to find multiple elements based on attribute value using title*=store for locating Our Stores link from the footer as shown below:

Step 2

Once the intended WebElement is located, we validate that the page has at least one element that matches the required locator. Cypress built-in assertion method .should(‘have.length.at.most’,1) is used for checking length value where ‘have.length.at.most’ in Cypress evaluates the length of the located element.

Step 3

The cy.get(‘a[title*=”store” i]’) method is used to find all the links on the page that contains the title “store”. In the screenshot shown below, I have highlighted two elements on the page that matched the required locator:

Step 4

The should() method is used for asserting if the length of the located WebElements is greater than 1. The length is checked using the have.length.gt method.

.each() in Cypress is used to iterate on each of the located WebElements. Here I am printing the href value using the attr([key]) method that returns the attribute value for the key provided as the argument.

As seen below, the URL of each element that is located on the page is printed on the console:

HTML class attribute is mostly used for styling the element or group of elements. Unlike ID, class attributes need not be unique, which is why this is helpful when we need to apply a common style to multiple elements.

In Cypress, class selectors can be identified using the following options:

Demonstration: Using ‘By Class’ in Cypress

Consider the following HTML Page for demonstration:

Shown below is the implementation that demonstrates the usage of ‘By Class’ in Cypress:

Code Walkthrough

Test 1: Interact with Elements using class selector

The cy.get(‘.item’) method is used to locate the element with class=”item”, which returns the list of elements matching the query.

Here is how the locator is identified using the Inspect tool in Chrome:

Test 2: Class selector short hand

We find the first product from the list of items and add that product to the cart. We then validate the product present in the cart, remove the product and verify if the cart is empty.

For this, we make use of regex with the class selector so that the code looks cleaner.

The above code locates the ‘Add to cart button’ on the home page and returns the first button using eq(0).

Once the button is visible, we click on the same by locating it using its title (i.e. ‘Proceed to checkout‘).

We add a Product to the cart by clicking on the ‘Proceed to checkout’ button.

Links are ways for connecting web resources (or web pages) to another through anchor tags (i.e., <a>) and href attributes. For example, as shown below, My Orders is the link text displayed on the page.

We can locate links in cypress using cy.get(<tags>:contains(‘<text>’)). Shown below is the sample implementation that demonstrates the usage of Link Text in Cypress:

Shown below is the execution screenshot, which indicates that the test execution is successful:

How to use the first() method in Cypress

Consider a scenario where you want to get the list of elements in DOM having a common pattern. For example, it could be items in the list, and you might be interested in fetching only the first item from the list.

To realize such a requirement, Cypress provides two approaches to get the first element in Cypress:

To demonstrate the usage of the first() method in Cypress, we get all the links under the “item” class and use the first() method to click the first from the list.

Shown below is the approach through which the first element is located on the desired web page:

Here is the execution snapshot:

How to use the last() method in Cypress

Akin to the first() method, Cypress’s last() method is used to locate the last element in a list of elements. This is a handy utility when working with applications like the ToDo app, where tasks are added at the end of the list and verification has to be done w.r.t the tasks’ addition (or deletion).

Shown below is the execution snapshot:

In the below HTML, <li> elements are grouped inside common <ul> and they all are at the same level from the root. These are called siblings. <ul> will be immediate parent to the lists while <div> will be parent to <ul> & <li>.

There are certain cases in automation where we might need to check the sequence of the items displayed on the page and for this, we can use the next() call in the chainable form in Cypress to find multiple elements and assert the sequence. Furthermore, similar to next(), we can use the prev() call to find previous siblings of selected elements.

nextUntil() and prevUntil() are the advanced ways of using the next() and prev() methods in Cypress. Suppose you want to validate the sequence of all the elements under siblings until some conditions set through selectors are not met. The nextUntil()/prevUntil() methods in Cypress validate the sequence of elements until certain conditions are met.

Shown below is the implementation that demonstrates the handling of ancestors and siblings using Cypress:

Shown below is the execution snapshot that indicates that the test execution was successful:

Here’s a short glimpse of the Cypress 101 certification from LambdaTest:

Although Cypress only supports CSS selectors by default, external packages are now available that let you use XPath with Cypress. To use Cypress XPath, perform the following steps:

Using XPath is very popular with automation frameworks to locate elements in DOM. In practice, XPath uses generic format of //<tag>[@attribute=value]

// is used in Cypress to find multiple elements anywhere in the DOM. It is also called the relative path. Similarly, there is ‘/’ , which can be used to find WebElement at an absolute location. <tag> is optional; if specified, all the elements matching the conditions will be returned.

@attribute is the attribute of the elements against which the match needs to be done. You can also use Cypress XPath functions like contains(), text(), etc., to use more advanced features to locate relevant WebElements.

Here is the sample implementation that demonstrates the usage of Cypress XPath [ i.e. cy.xpath() ]:

Shown below is the execution snapshot:

Cypress has another useful feature for users that helps locate CSS selectors easily on pages directly from the test runner. Selector Playground will always match and find the unique locators for the elements to not create an issue when using them.

Shown below is the priority of the unique locators that Cypress supports:

Where data-* are the cypress recommended attributes added to the WebElements to isolate the elements from JS/CSS changes that might break the test.

Cypress is a cutting-edge browser automation solution that is fast gaining the attention of the software community. It offers a better, more effective approach to web testing and is gaining popularity due to its ability to help teams keep pace with a complete range of application testing.

By using Cypress, you can take advantage of all built-in locators and features like intelligent matching and asynchronous commands to ensure that each test has no dependencies. In this Cypress tutorial, we have seen how we can use Cypress locators to access WebElements in the DOM for realizing Cypress automation tests. Moreover, although Cypress is built with a strict “no CSS selectors allowed” stance internally, external community packages now exist that allow you to write Cypress tests using XPath.

Happy Testing!

Add a comment

Related posts:

Flex Box in React Native

Watsup party people! I spent some of my spare time this Friday going over React Native and why it is so popular. In my opinion, it will be the future of mobile software engineering. It is the go to…

How Do I Know?

Your lap is the perfect pillow It has a marvelous view From here I see a big tall tree with roots reaching the underground edges of eternity My eyes devour the strength of you Permanent, reassuring…

Affiliate News

Here are some of the affiliate, referral and influencer marketing news you may have missed last week… To make your partnerships work for you in 2021, start with an audit of your affiliate program…