top of page
hand-businesswoman-touching-hand-artificial-intelligence-meaning-technology-connection-go-

Unleashing the Power of Cypress Testing- Part 2





Introduction

In the previous blog post, we delved into the world of Cypress, exploring the effortless installation process and uncovering the numerous advantages that make Cypress a standout choice for modern web automation testing. If you missed that post, I highly recommend checking it out here to gain insights into getting started with Cypress.


This blog will help in gaining quick proficiency and on-the-go confidence in handling Cypress-related queries and scenarios. Elevate your understanding and preparation effortlessly in your Interview!


In Cypress, web locators are not explicitly used as in traditional Selenium-based frameworks. Instead, Cypress encourages the use of more dynamic and resilient methods to locate elements on the page. It's built on the concept of "Cypress Commands" that allow you to interact with and assert on elements in a more natural and robust way.

However, there are certain strategies and commands that you can use to select and interact with elements, similar to how you might use locators in other frameworks.


Examples of Cypress Element Selection:

I- Web Locators:


1. Using CSS Selectors:

// Select by class

cy.get('.my-class');


// Select by ID

cy.get('#my-id');


// Select by attribute

cy.get('[data-test="my-element"]');


2. Using XPath (Not Recommended, but Possible):

While Cypress does not encourage XPath, you can still use it:

cy.xpath('//button[@id="my-button"]');


3. Combining Commands for More Specific Selection:

// Selecting a specific child element

cy.get('.parent-class').find('.child-class');


// Selecting based on text content

cy.contains('Submit');


// Using chaining to refine selection

cy.get('.parent-class').find('.child-class').eq(1);


Advanced Locators:

1. Using Data Attributes:

// Select by data attribute

cy.get('[data-test="submit-button"]');


  • Usage Explanation:

  • This command selects an element with a specific data-test attribute value.

  • For example, if you have HTML like <button data-test="submit-button">Submit</button>, this command will target that button.

2. Using Cypress Custom Commands:

// In your support/commands.js file

Cypress.Commands.add('submitBtn', () => {

  return cy.get('[data-test="submit-button"]');

});


// In your test

cy.submitBtn().click();


Usage Explanation:

  • This example demonstrates creating a custom command named submitBtn that returns a specific element using a data-test attribute.

  • The custom command is then used in the test with cy.submitBtn() to select the element and click() to interact with it.

  • Custom commands promote code reusability.


The concept of selecting sibling elements is important when you want to interact with elements that share the same parent. Here are some examples:

Selecting Sibling Elements:

1. Using next or prev Commands:

// Select the next sibling

cy.get('.current-element').next('.sibling-element');


// Select the previous sibling

cy.get('.current-element').prev('.sibling-element');


  • Explanation:

  • The next command selects the next sibling of the current element that matches the provided selector.

  • The prev command selects the previous sibling of the current element that matches the provided selector.

  • For example, if you have HTML like <div class="current-element"></div><div class="sibling-element"></div>, these commands will target the sibling element.

2. Using siblings Command:

// Select all siblings

cy.get('.current-element').siblings();


// Select specific siblings based on a selector

cy.get('.current-element').siblings('.sibling-element');


  • Explanation:

  • The siblings command selects all siblings of the current element.

  • By providing a selector as an argument, you can narrow down the selection to specific siblings.

  • For example, if you have HTML like <div class="parent"><div class="current-element"></div><div class="sibling-element"></div></div>, these commands will target the sibling elements.

3. Using first or last Commands with siblings:

// Select the first sibling

cy.get('.current-element').siblings().first();


// Select the last sibling

cy.get('.current-element').siblings().last();


Explanation:

  • The first command selects the first sibling from the set of siblings.

  • The last command selects the last sibling from the set of siblings.

  • For example, if you have HTML like <div class="parent"><div class="current-element"></div><div class="sibling-element"></div></div>, these commands will target the first and last sibling elements.

Real-world Example:

Suppose you have the following HTML structure:

<div class="parent">

  <div class="current-element">Current Element</div>

  <div class="sibling-element">First Sibling</div>

  <div class="sibling-element">Second Sibling</div>

  <div class="sibling-element">Third Sibling</div>

</div>


You can use Cypress commands to interact with the sibling elements:

// Select and assert the text of the second sibling

cy.get('.current-element').siblings('.sibling-element').eq(1).should('have.text', 'Second Sibling');


This command first selects the current element's siblings with the class "sibling-element," then filters to the second sibling using eq(1), and finally asserts that it should have the text "Second Sibling."

These strategies should cover most scenarios where you need to work with sibling elements in Cypress.



These usage explanations illustrate how Cypress commands can be used to select elements on the page in various ways, depending on the structure and attributes of your HTML. Cypress commands automatically wait for elements to be available, reducing the need for explicit waits in your tests.


II- Conditional Commands:


Cypress provides a variety of commands to interact with web elements and retrieve information about the current state of the application. Here are examples of some commonly used Cypress commands for retrieving information:

1. Get URL:

// Get the current URL

const currentURL = Cypress.url();

console.log('Current URL:', currentURL);

Usage Explanation:

  • The Cypress.url() command is used to retrieve the current URL of the application.

  • The URL is then stored in the currentURL variable.

  • The console.log statement is used to output the current URL to the console.



2. Get Title:

// Get the title of the current page

cy.title().then((title) => {

  console.log('Page Title:', title);

});

3. Get Current URL:

// Get the current URL

cy.url().should('include', 'example.com');


Usage Explanation:

  • The cy.url() command is used to retrieve the current URL.

  • The .should('include', 'example.com') assertion ensures that the URL includes the specified substring ('example.com' in this case).

  • This is a common way to assert the expected state of the URL during a test.



4. Get Page Source:

// Get the page source

cy.document().then((doc) => {

  const pageSource = new XMLSerializer().serializeToString(doc);

  console.log('Page Source:', pageSource);

});

Usage Explanation:

  • The cy.document() command is used to retrieve the document object of the current page.

  • The .then() function is used to handle the asynchronous nature of Cypress commands.

  • The page source is obtained by serializing the document object to a string using XMLSerializer.

  • The page source is then logged to the console.



5. Get Window ID:

// Get the current window ID

cy.window().then((win) => {

  const windowId = win.id;

  console.log('Window ID:', windowId);

});

Usage Explanation:

  • The cy.window() command is used to retrieve the window object of the current page.

  • The .then() function is used to handle the asynchronous nature of Cypress commands.

  • The window ID is obtained from the window object and logged to the console.


In Cypress, many commands are asynchronous, meaning they do not execute immediately. They operate in the Cypress command queue, and the test runner needs a way to handle the results of these commands once they are resolved.

The .then() function in Cypress is used to work with the results of a preceding command. It allows you to execute a callback function once the previous command has completed and its result is available. Since JavaScript is single-threaded and uses an event-driven, asynchronous model, using .then() helps manage the flow of asynchronous operations.

Here's a breakdown of what it means:

  • Handling Asynchrony:

  • Cypress commands operate asynchronously because they interact with the browser, which is an inherently asynchronous environment. For example, fetching the title of a page or the value of an element involves waiting for the browser to respond.

  • Chaining Commands:

  • Cypress encourages a fluent, chainable syntax. Commands are often chained together to create a sequence of operations.

  • The .then() function allows you to attach a callback function to a command, specifying what should happen with the result of that command.

  • Callback Function:

  • The callback function provided to .then() will be executed once the preceding command has completed.

  • It receives the result of the preceding command as an argument. You can then perform additional actions or assertions based on that result.


Cypress provides a set of commands that implicitly handle waiting for elements to appear, become visible, or fulfill certain conditions. These commands include should, invoke, and its, among others.


1. Checking Visibility (isVisible-like behavior):

To check if an element is visible, you can use the should command with the be.visible assertion.

cy.get('.my-element').should('be.visible');

Usage Explanation:

  • The cy.get('.my-element') command selects the DOM element with the class "my-element."

  • .should('be.visible') asserts that the element should be visible.


2. Checking if an Element is Displayed:

Cypress doesn't have a direct command like isDisplayed, but you can achieve a similar check using the should command.

cy.get('.my-element').should('exist');

Usage Explanation:

  • The cy.get('.my-element') command selects the DOM element with the class "my-element."

  • .should('exist') asserts that the element should exist in the DOM.

3. Checking if an Element is Selected (for checkboxes or radio buttons):

For checkboxes or radio buttons, you might want to check if they are selected. Use the should command with the be.checked assertion.

cy.get('#my-checkbox').should('be.checked');

Usage Explanation:

  • The cy.get('#my-checkbox') command selects the checkbox with the id "my-checkbox."

  • .should('be.checked') asserts that the checkbox should be checked.

4. Checking Specific Conditions (invoke command):

You can use the invoke command to perform specific checks or actions on an element.

cy.get('.my-element').invoke('css', 'display').should('not.equal', 'none');

Usage Explanation:

  • The cy.get('.my-element') command selects the DOM element with the class "my-element."

  • .invoke('css', 'display') gets the value of the CSS 'display' property of the element.

  • .should('not.equal', 'none') asserts that the 'display' property should not be 'none'.


III- Navigational Commands:

Cypress provides a set of navigational commands that allow you to interact with the browser's navigation history. Here are some commonly used navigational commands:

1. Navigate Back:

// Navigate back in the browser's history

cy.go('back');


  • Explanation:

  • The cy.go('back') command simulates the user clicking the browser's back button.

  • This command is equivalent to manually navigating back in the browser history.

2. Navigate Forward:

// Navigate forward in the browser's history

cy.go('forward');


  • Explanation:

  • The cy.go('forward') command simulates the user clicking the browser's forward button.

  • This command is equivalent to manually navigating forward in the browser history.

3. Navigate To a Specific URL:

// Navigate to a specific URL


  • Explanation:

  • The cy.visit('https://www.example.com') command loads the specified URL in the browser.

  • This command is used to navigate directly to a specific URL.

4. Refresh the Page:

// Refresh the page

cy.reload();


  • Explanation:

  • The cy.reload() command refreshes the current page.

  • This command is equivalent to manually refreshing the page using the browser's refresh button.

Example Usage:

// Visit an initial URL


// Click a link that navigates to another page

cy.get('a').click();


// Navigate back to the initial page

cy.go('back');


// Navigate forward to the second page

cy.go('forward');


// Reload the current page

cy.reload();


This blog has been a dedicated exploration into the foundational elements of Cypress—WebLocators, Conditional, and Navigational Commands—essential components that form the bedrock of effective testing strategies.


As we wrap up this segment of our Cypress journey, it's important to acknowledge that what we've covered is just the tip of the iceberg. The vast Cypress toolkit awaits, with additional commands such as Mouse Actions, Screenshots, and Videos, promising an even richer testing experience.


Happy testing, and stay tuned for the next chapter!


12 views0 comments

Recent Posts

See All

Comments

Rated 0 out of 5 stars.
No ratings yet

Add a rating
bottom of page