Reusing Locators | Bondar Academy
Course: Cypress UI Testing with JavaScript
Module: Interaction with Web Elements
Instructor: Artem Bondar
Lesson Summary
In this lesson, we explore two fundamental concepts of the Cypress framework related to variable management and function results. Understanding these concepts is crucial for effectively using Cypress, as traditional approaches from other frameworks may lead to frustration. Key Concepts 1. Cypress Alias The first concept is the Cypress alias , a smart global variable that allows you to save locators for later use. Instead of using traditional constants, you can create an alias using the as method: cy.get('locator').as('inputEmail1'); To use the alias, reference it with an @ sign: cy.get('@inputEmail1').click(); This alias is globally accessible throughout the test run, simplifying the reuse of locators without the need for constant assignments. 2. Using Cypress Then Method The second concept involves the Cypress then method, which returns a jQuery object. To interact with the DOM using Cypress methods, you must convert this jQuery object back into a Cypress chainable object using: cy.wrap(jQueryObject); For example: cy.get('locator').then((inputEmail) => { cy.wrap(inputEmail).parents('selector').click(); }); Additionally, remember that you cannot return values directly from the then method. Instead, use aliases to store values for later use. Summary Use Cypress alias for saving locators globally. Utilize the then method with cy.wrap to convert jQuery objects back to Cypress chainables. Mastering these concepts will enhance your Cypress testing experience and reduce flaky tests.