Cypress .should() Command: A Detailed Guide

Anshita Bhasin

Posted On: May 7, 2024

view count114381 Views

Read time30 Min Read

In Cypress, an assertion is a way to validate that the Application Under Test (AUT) is functioning as expected. For this, the Cypress .should() command is used to make assertions about the state of your Application Under Test. It verifies if certain conditions are met before your test proceeds further.

Typically, an assertion consists of two parts: a target value (the actual value being tested) and an expected value (the expected result of the test). If the target value matches the expected value, the assertion passes, indicating that the application functions as expected. However, if the target value does not match the expected value, the assertion fails, indicating that something is wrong with the application, and the test fails.

In this Cypress tutorial, we look at how to use the Cypress .should() command and some real-time use cases.

What are Assertions?

Assertions are used to define the expected behavior or outcome of a test. When the test results deviate from the expected behavior, the assertions fail, indicating a mismatch between the actual and expected outcomes.

Let’s take an example scenario where you have an eCommerce website, and your objective is to validate that the number of products displayed on the page is exactly 10. But, if you don’t have any assertion in place. You will miss verifying the total count of products, which can lead to misleading results.

It is the most important part of test execution. As a tester, your primary responsibility is to ensure the seamless functionality of the application. If the Application Under Test results do not align with the expected outcome, it is crucial to report any bugs or discrepancies. This practice plays a vital role in upholding the reliability and quality of the web application.

Assertions are essential as they contribute to early issue detection, effective debugging, and improved code quality. By incorporating assertions into testing processes, testers can enhance the overall quality and reliability of the web application. You can learn more about assertions through this tutorial on Cypress assertions.

Subscribe to the LambdaTest YouTube Channel for the latest updates on tutorials around Selenium testing, Cypress testing, and more.

Why Use Cypress .should() Command?

Cypress provides its custom assertion library, which extends the Chai assertion library. One of the assertion commands provided by Cypress is .should().

The Cypress .should() command is used to make assertions about the state of the AUT. It ensures that certain conditions are met before proceeding with the test.

These assertions are automatically retried until they pass or the command times out. This means that if an assertion fails initially, Cypress will retry it until the test passes or the command results in a time out of 4000ms. It makes tests more resilient to flakiness caused by timing issues or network latency.

Syntax:

Cypress .should() Command

Here are some examples that demonstrate the usage of the Cypress .should() command with cy.get(), cy.contains(), and cy.wrap():

demonstrate the usage of the Cypress .should() command

Looking to make your testing process smoother and more efficient? KaneAI by LambdaTest can help. It allows you to create and manage test cases using natural language, simplifying the process of defining conditions and assertions.

KaneAI is an AI end-to-end test assistant designed to streamline test automation. It allows users to create, manage, and debug test cases using natural language, making the testing process more intuitive and accessible. KaneAI is built for high-speed quality engineering teams and integrates seamlessly with LambdaTest’s suite of tools for test execution, orchestration, and analysis.

Differences: Cypress .should() and .then() Command

When working with Cypress, you may come across two commonly used terms: .should() and .then() command. While they may appear similar at first glance, they serve distinct purposes and offer unique functionalities.

Let’s look at the difference between Cypress .should() and .then() commands.

Feature should() then()
Chaining Commands Requires being chained off a previous command. Requires being chained off a previous command.
Assertion Retry Retries its specified assertions until they pass or time out. Does not retry its assertions.
Timeouts Continues to retry its specified assertions until it times out. Can time out waiting for a promise to resolve.
Command Logging Logged in the command log, providing a clear overview of the test’s execution. Does not log in the command log.
Purpose/Functionality Specialized logic to rerun the callback function until all assertions pass. Enables working with the yielded subject from the previous command, suitable for value manipulation or executing actions.
Syntax .should(chainers)

.should(chainers, value)

.should(chainers, method, value)

.should(callbackFn)

.then(callbackFn)

.then(options, callbackFn)

Handle Assertions Using Cypress .should() Command

In this blog, I will use the cy.get() for .should() assertion. Assertion can be handled in different ways.

Below are the most commonly used ways to handle assertion in Cypress:

  • Assert based on class value.
  • Assert based on length.
  • Assert based on text.
  • Assert based on the value tag.
  • Assert based on HTML attribute.
  • Assert for checkboxes.
  • Chaining multiple assertions.
  • Assert if the text is visible/hidden.
  • Assert if the value is empty.
  • Assert if the URL is correct.
  • Assert if the element is not present.

Assert Based on Class Value

To perform assertions where the class of an element can change dynamically based on user interactions or other events, you can use Cypress .should(‘have.class’, ‘className’) command. This command allows you to verify that an element has the expected class. By specifying the desired class name, you can assert whether the element possesses that class as part of your test validation.

It can be useful if the UI changes dynamically based on user interactions or application state. By asserting specific class values, you can ensure the expected behavior is upheld. For example, you can verify whether a button appropriately includes the disabled class when specific conditions require it to be disabled.

An additional scenario where the Cypress .should() command can be used is when your application exhibits various states indicated by different class values. In such cases, you can employ assertions to validate the transitions between these states.

For example, you can verify that an element has the loading class during an asynchronous operation and then changes to the loaded class when the operation is complete.

Syntax:

Assert Based on Class Value

It can be used with Document Object Model (DOM) commands like cy.get(), cy.contains(), or cy.wrap(), as shown below:

Assert Based on Class Value

Below is an example of how to use the assertion with cy.get() in Cypress.

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground.
  2. Enter the email address in a textbox and verify the class value is as expected.
  3. Enter the password in the textbox.
  4. Verify the class value of the submit button is as expected.

Implementation:

Below is the Cypress code to open the web application and verify the class using the Cypress .should(‘have.class’,className) assertion.

Github

Test Execution:

Test execution Cypress .should(‘have.class’,className) assertion

cypressClassAssertions

Code Walkthrough:

Step 1: Firstly, the test navigates to the URL of the website using cy.visit().

navigates to the URL of the website using cy.visit()

Step 2: In the below code snippet, the initial step involves selecting the input field with the id input-email. Subsequently, a test email address is entered into the selected field.

Finally, the validation process checks whether the input field possesses the form-control class by utilizing the Cypress .should(‘have.class’, ‘form-control’) command.

It should be noted that although an ID is utilized as a locator in this particular example, you can also create CSS based on other HTML attributes if desired, providing further flexibility.

CSS based on other HTML attributes

Step 3: As shown in the screenshot below, the class name of the locator is form-control in DOM. So, in the Cypress .should() command, the same class name is passed along with the locator of the element on the web page.

 form-control in DOM.

Step 4: In the below code, I select the password input field and then type in a test password.

select the password input field

Step 5: The last line selects the login button on the page using a CSS Selector and then checks that it has the classes btn and btn-primary.

login button on the page using a CSS Selector

login button on the page using a CSS Selector

As shown above, the class value of the locator is btn btn-primary, which is passed in the Cypress .should() command.

Assert Based on Length

In Cypress, if you want to handle a scenario where you want to verify the expected number of elements for a specific set of elements, you can use the Cypress .should(‘have.length’,totalLength) command.

For example, it can be helpful in cases where you have multiple products on the page and want to check the length of it or if you wish to verify the number of search results. It is also helpful in cases where you want to check the number of products in a shopping cart.

Assert Based on Length

Syntax:

syntax Assert Based on Length

Let’s understand in detail with a test scenario.

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground webpage using cy.visit().
  2. Verify that there are six categories displayed on the page using the .should(have.length) assertion.
  3. Verify that there are 10 top products displayed on the page.

Implementation:

Test Execution:

Test Execution: Assert Based on Length

cypresslengthAssertions

Code Walkthrough:

Step 1: Firstly, the test navigates to the URL of the website using cy.visit().

 navigates to the URL of the website using cy.visit()

Step 2: Then, it verifies that there are six categories displayed on the page using the .should(have.length) assertion on the class value, which is .navbar-nav.horizontal >li.

.should(have.length) assertion

In the screenshot below, it can be seen that the category locator with class value .navbar-nav.horizontal >li has six results.

category locator with class value .navbar-nav.horizontal >li

category locator with class value .navbar-nav.horizontal >li

Step 3: Next, it verifies that there are 10 top products displayed on the page using the .should(have.length) assertion on the class locator, which is .swiper-wrapper.

class locator, which is .swiper-wrapper.

As shown below in the screenshot, cy.get(‘.swiper-wrapper’).eq(1) is used, which returns the matched element, which is at location 2.

screenshot, cy.get(‘.swiper-wrapper’).eq(1)

Step 3: It is seen in the below screenshot that the div element count is ten, which is inside cy.get(‘.swiper-wrapper’).eq(1).find(‘>div’).

screenshot that the div element count is ten

en in the below screenshot that the div element count is ten

The below command cy.get(‘.swiper-wrapper’).eq(1).find(‘>div’).should(‘have.length’, 10) searches for the element with class value .swiper-wrapper, which is at index 1 (or location2) and then finds the div elements and in the end it verifies that the total number of div elements are 10 using .should(‘have.length’,10).

cy.get(‘.swiper-wrapper’).eq(1).find(‘>div’).should(‘have.length’, 10)

Assert Based on Text

In Cypress, if you want to verify the expected text on the page, you can use Cypress .should(‘have.text’,expectedText) assertion. This is one of the most commonly used Cypress assertions.

It is helpful in cases where your application supports multiple languages. In those cases, you can use text-based assertions to verify the correct translation of text elements. By asserting the presence of specific translated text, you can ensure that the application displays the correct language based on the user’s preferences.

This type of assertion is frequently used in testing when a tester needs to verify an expected value, often in the form of text, on a web page. As such, assertions based on text can be used in a wide range of scenarios where verifying expected text is a critical part of the test case.

Syntax:

Assert Based on Text

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Verify that the text Upto 30% Off on Popular Smartphones + Exchange Offers is displayed under the TOP PRODUCTS section.
  3. Verify that the third product displayed under the TOP COLLECTION section is HTC Touch HD.

Implementation:

Test Execution:

test execution Assert Based on Text

cypressTextAssertions Assert Based on Text

Code Walkthrough:

Step 1: Firstly, the test navigates to the URL of the website using cy.visit().

navigates to the URL of the website using cy.visit().

Step 2: It uses the cy.get() command with a class selector to target an element on the page with the class m-md-0.d-flex align-items-center.mb-3.

Then, the Cypress .should() command is used with the assertion have.text to check that the element contains the expected text Upto 30% Off on Popular Smartphones + Exchange Offers.

Cypress .should()

As shown in the screenshot below, locator values have matching text. It is important to note in the case of Cypress .should(‘have.text’expectedText) assertion, you need to pass the exact text value, or else your test case will fail. Even if there is space in the text, the test case will fail in that case.

Cypress .should(‘have.text’expectedText)

Cypress .should(‘have.text’expectedText)

Step 3: The last line of code verifies the text of a specific product located at a specific location on the page. It finds the particular location using class .swiper-slide.swiper-slide-active at location 3. Then, it finds the first text, which is under the element (‘>div>div>h4>a‘).

In the end, it asserts the text of the link using the Cypress .should(‘have.text’, ‘HTC Touch HD’) assertion.

Cypress .should(‘have.text’, ‘HTC Touch HD’)

In the screenshot below, it can be seen for the locator with class .swiper-slide.swiper-slide-active, which is at the 3rd location, inside that div>div>h4>a has specific text, which we are validating in our code.

3rd location, inside that div>div>h4>a has specific text

Cypress .should() command with the have.text assertion.

In summary, this test case navigates to a website and verifies that two elements on the page contain expected text using the Cypress .should() command with the have.text assertion.

Assert Based on Value Tag

It is a common practice in web applications to assert based on the value tag, which sets the initial value of an input element, such as a text input field, to validate whether an element contains a specific value.

This can be easily achieved using the Cypress .should(‘have.value’,expectedValue) command, which verifies whether a particular element has the expected value.

It can be used in cases when you are interacting with select dropdowns. You can verify that the selected option’s value matches the expected value. This is useful for validating the correctness of user selections in dropdown menus.

Syntax:

Assert Based on Value Tag

Let’s understand it with the below examples.

Test Scenarios:

  1. Navigate to the LambdaTest eCommerce Playground website using cy.visit().
  2. Enter text in a search box using cy.type().
  3. Verify the entered text value is correct.
  4. Also, verify if the entered text is not equal to some other value. It is case-sensitive.
  1. Navigate to the Dropdown Demo page of Selenium Playground.
  2. Select the dropdown value..
  3. Verify the selected dropdown value is as expected.

Implementation:

Test Execution:

Test execution Assert Based on Value Tag

CypressValueAssertions Test execution Assert Based on Value Tag

CypressValueAssertions Test execution Assert Based on Value Tag

CypressValueAssertions Test execution Assert Based on Value Tag

Code Walkthrough:

Test Case 1

In the first test case, it opens a web application. Enter the text and verify if the entered text value matches the expected value.

Step 1: The first step is to navigate to the URL using cy.visit().

first step is to navigate to the URL

Step 2: Using cy.get(selector), it will find the element and then using .type(‘iphone’), will pass the text to the textbox.

Using cy.get(selector)

Step 3: After entering the text in the textbox, it verifies if the entered text matches the expected text using .should(‘have.value’,expectedText).

text using .should(‘have.value’,expectedText)

Test Case 2

In the second test case, it opens a web application. Select the value from the dropdown and verify if the selected text value matches the expected value.

Step 1: The first step is to navigate to the URL using cy.visit().

navigate to the URL using cy.visit().

Step 2: Using the below code, choose the value of the dropdown. In this case, .select() is used to select the dropdown value.

value of the dropdown

Step 3: In the end, assert the selected dropdown value is as expected using Cypress .should(‘have.value’,expectedText) command.

Cypress .should(‘have.value’,expectedText) command

Assert Based on Attribute

It’s often important to verify that certain attributes of elements on the page have the expected values.

For example, if you have a link on the page and want to assert that the value of the href attribute is correct, Cypress makes it easy to do this using its built-in .should() function.

To assert based on an attribute, you can use the should function with the have.attr property. The have.attr property allows you to check the value of any attribute on an element.

Syntax:

Example of asserting based on attribute in Cypress

Let’s understand with below test scenario:

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Select a dropdown value.
  3. Verify the selected dropdown value is as expected.

Implementation:

Test Execution:

LambdaTest eCommerce Playground website test scenario Cypress Assertions implementation and execution code

Cypress Assertions Test Scenario and Implementation Code Snippet

Code Walkthrough:

Step 1: In the first step, the cy.visit() command is used to navigate to the specified URL.

Screenshot demonstrating the use of cy.visit() command to navigate to a specified URL

Step 2: The cy.get() command is used to select the element on the web page containing the text Home, which in this case is a span element.

Example of using cyget command to select the Home element on a webpage

As shown below, .parents(‘a’) Cypress command is used, which traverses up the DOM tree from the span element to select its parent element, which is an a tag.

Illustration of the parents a Cypress command traversing up the DOM tree from a span element to select its parent a tag

In the end, the Cypress .should() command is used to assert that the a tag selected in the previous step has a specific attribute called href, with a value of https://ecommerce-playground.lambdatest.io/index.php?route=common/home.

Illustration of Cypress should command asserting href attribute value

So overall, this code navigates to the website, selects the Home link, and checks if its href attribute has a specific value.

Code snippet demonstrating website navigation and link verification

Assert Based on Checkboxes

When it comes to testing forms, checkboxes are a common element that should be included. As a test automation engineer, we need to assert the expected behavior of the checkboxes in our test cases.

In scenarios where mandatory terms and conditions checkboxes are required for user login, you can utilize the Cypress .should(‘be.checked’) assertion to verify whether the checkbox is selected before proceeding with the login process. This approach ensures that the user can proceed only when the checkbox is checked, the user can proceed.

Additionally, this approach proves useful when you need to confirm that a checkbox has been unchecked. For instance, certain web applications provide a checkbox during registration to receive notifications via email. Users have the option to opt out of this feature. By employing the Cypress .should(‘be.unchecked’) command, you can verify whether the already selected checkbox can be successfully deselected.

Syntax:

Assert Based on Checkboxes - Testing Forms with Cypress

Let’s understand in detail how to write assertions for checkboxes using Cypress using the below scenario.

Test Scenario:

  1. Navigate to the Checkbox Demo page.
  2. Select a single checkbox and validate if it got checked.
  3. Select multiple checkboxes on the page.
  4. Verify that all the checkboxes were selected/checked.
  5. Uncheck the single checkbox and verify it got unchecked.
  6. Uncheck the multiple checkboxes and verify if they got unchecked.

Implementation:

Test Execution:

Checkbox Demo page screenshot

Screenshot of Checkbox Demo page

Code Walkthrough:

The above code verifies that the checkboxes on the provided webpage can be selected and unselected correctly.

Step 1: The cy.visit() command is used to navigate to the specified URL.

Screenshot of code verifying checkbox selection and unselection on a webpage

Step 2: The cy.get() command is used to select the element on the webpage, along with the .check() command, which is used to select the checkbox. Then, the Cypress .should(‘be.checked’) command is used to assert that the checkboxes are checked.

Cypress code snippet demonstrating checkbox selection and assertion

Cypress commands for selecting and checking checkboxes on a webpage

Screenshot illustrating the use of Cypress commands cyget and check to select and check checkboxes on a webpage

Screenshot demonstrating the use of Cypress commands cyget check and should(bechecked) to interact with checkboxes on a webpage

Step 3: The cy.get() command is used to select the element on the web page along with the .uncheck() command to uncheck the checkboxes.

Then, the Cypress .should(‘not.be.checked’) command is used to assert that the checkboxes are unchecked.

Demonstration of using Cypress commands to uncheck checkboxes and assert their unchecked state

Handle Multiple Assertions Using Cypress .should() Command

In Cypress, using the chaining method, you can easily perform multiple assertions on the same element or group of elements. This makes it possible to write more concise and efficient tests.

Chaining in Cypress should be used when you want to perform multiple assertions on an element or a series of actions in a specific order. It allows you to express the expected behavior of your web application in a concise and readable manner.

For example, You can use multiple assertions on the same element using the chaining method for a case where you want first to verify if there are eight products on the page. Then you want to perform a second assertion to validate the text of each product.

By chaining multiple assertions together, you can create a sequence of conditions that need to be satisfied for the test to pass. In this case, each assertion in the chain is executed sequentially, and the next assertion is only evaluated if the previous one passes.

It is important to note if any assertion in the chain fails, the test will immediately fail and stop executing further assertions. In Cypress, if there is a failure case in the chain, the test will stop the execution at that point, and the failure will be reported in the test results.

Let’s understand this with the below example of how to perform multiple assertions on an element using the chaining method:

Test Scenarios:

Test Case 1

  1. Navigate to the Checkbox Demo page of Selenium Playground.
  2. Verify that the Top Trending Category products on the page are eight in the count and verify that the last element is MP3 Players and has a CSS font-family.
  3. Verify that the search box has the attribute aria-label and the value Search For Products.
  4. Enter the text in the search box and verify the entered text is as expected.
Test Case 2

    Navigate to the Dropdown Demo page of Selenium Playground.
    Select the dropdown value Wednesday from a single dropdown and verify that the element got selected and has the same value which was selected.

Implementation:

Test Execution:

Selenium Playground Checkbox Demo page

Selenium Playground Dropdown Demo page

Cypress Assertions Implementation Screenshot

Code Walkthrough:

Test Case 1

Step 1: The cy.visit() command is used to navigate to the specified URL.

Screenshot demonstrating navigation using cy visit command to specified URL

Step 2: The first assertion cy.get(‘.figure.img-top’).should(‘have.length’, 8) verifies that there are eight elements with the class figure img-top.

Verification of Eight Elements with 'figure img-top' Class

Assertion for Eight Elements with Specific Class

The second assertion .last().should(‘include.text’, “MP3 Players”) verifies that the last element with the class figure img-top contains the text MP3 Players.

Image depicting code snippet verifying text 'MP3 Players' in last element with class 'figure img-top

Code validation Last image element checks for 'MP3 Players' text presence

The third assertion .should(‘have.css’, ‘font-family’) verifies that the font family of the last element with the class figure img-top is defined.

Code Snippet for CSS Font Family Check

Step 3: As per the below code, first assertion cy.get(‘input[name=”search”]’). first().should(‘have.attr’, ‘aria-label’, “Search For Products”) verifies that the first input element with the name attribute search has an aria-label attribute set to Search For Products.

Screenshot of code demonstrating assertion for aria-label attribute on search input element

The second assertion .type(‘iphone’).should(‘have.value’, ‘iphone’) types the value iphone into the first input element with the name attribute search and then verifies that the input value is set to iphone.

Automated Testing Typing 'iphone' into Search Field

Test Case 2

Step 1: The cy.visit() command is used to navigate to the specified URL.

Code snippet cy visit command for URL navigation

Step 2: As per the below code, cy.get(‘#select-demo’).select(‘Wednesday’) selects the option Wednesday from the dropdown menu with the ID select-demo.

Code snippet showing selection of Wednesday from dropdown menu

Step 3: The below code cy.get(‘#select-demo option:selected’).should(‘be.selected’).and(‘have.value’, ‘Wednesday’) verifies that the selected option is Wednesday and that it is marked as selected.

Code snippet showing Cypress command verifying selected option is Wednesday

Assert if the Text Is Visible/Hidden

To verify if the DOM element is visible on the page. In Cypress, the .should(‘be.visible’) command is used. This assertion can be used to ensure that certain UI elements are displayed correctly and that the user can interact with them as expected.

This is helpful in cases where you want to verify the content on the page. For example, after successful registration, you can verify if the name entered while registering is the same. It can also be used in cases where you want to verify that a successful message is displayed or not.

You can check both the cases about visibility and non-visibility of an element.

For non-visibility, it can be helpful in cases where you want to verify if an element is not visible on the page. For example, if you want to verify the error text on the page is not visible. In that case, you can use the Cypress .should(‘not.be.visible’) command.

Syntax:

Cypress should be visible command example

Let’s understand the below test scenario.

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Verify on the web page that the category Home is visible.
  3. Verify if a modal dialog is hidden on the page.

Implementation:

Test Execution

LambdaTest eCommerce Playground website screenshot

Cypress Assertions code snippet

Code Walkthrough:

Step 1: The cy.visit() command is used to navigate to the specified URL.

Code walkthrough Step 1 cy visit command navigating to specified URL

Step 2: As per the code in the below screenshot, the cy.get() command is used to select the element on the webpage along with the Cypress .should(‘be.visible’) command, which asserts that the text is visible on the page.

cypress-get-assert-visible

Step 3: As per the code in the below screenshot, the cy.get().should(‘not.be.visible’) command is used to check that a modal dialog is hidden. Modal dialogs are often used in web applications to display important messages or prompts to the user.

web-application-modal-dialog

It is important to note that by using the Cypress .should(‘not.be.visible’) assertion, you can ensure that it is hidden from the user when it is not needed.

Assert if the Value Is Empty

In Cypress if you want to verify if a value is empty or not, based on the value for the input field or text content or URL. You can use Cypress .should(‘be.empty’) command.

Some of the most common use cases where Cypress .should(‘be.empty’) can be used are:

  • Validating Cleared Fields: After interacting with an input field and clearing its value, you can assert that the field is empty using the Cypress .should(‘be.empty’) command. This confirms that the field has been successfully cleared.
  • Verifying Empty Lists or Tables: If you have lists or tables dynamically populated with data and you want to assert that they are empty under specific conditions, you can use the Cypress .should(‘be.empty’) command.
  • Testing Empty Input Fields: When testing forms or input fields, you can use Cypress .should(‘be.empty’) to verify that an input field starts with no value. This ensures that users start with a blank input field before entering data.

Syntax:

Cypress_Should_Be_Empty_Command_Example

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Verify the URL hash is being used correctly.

Implementation:

Test Execution:

LambdaTest eCommerce Playground homepage

Empty URL hash verification on LambdaTest eCommerce Playground

Cypress testing the URL hash

Code Walkthrough:

Step 1: The cy.visit() command is used to navigate to the specified URL.

Code walkthrough illustration A browser window displaying a URL

Step 2: cy.hash() is a command that retrieves the current URL hash. The URL hash is part of the URL that comes after the # symbol, and it is often used to store data that is used by JavaScript on the client side.

The Cypress .should(‘be.empty’) assertion checks that a value is empty. When applied to cy.hash(), it checks that the current URL hash is empty.

In the below code, this assertion is used to verify that a page has not been loaded with a specific URL hash.

Cypress Code Example

Assert if the URL Is Correct

As a tester, one of the most common assertions you perform is verifying if the URL of the page is valid. There are no additional parameters added to the URL after opening the web application.

If you want to verify the URL, there is Cypress .should() command, which can be used with cy.url(). You can either match the exact URL or match some of the URL contents using cy.url().should() assertion.

Syntax:

Assert if the URL Is Correct

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Verify that the URL of the website is the same as the expected text.
  3. Verify that the URL of the website includes the expected text in the URL.

Implementation:

LambdaTest eCommerce Playground website homepage

Test Execution:

URL verification during LambdaTest eCommerce Playground testing

Test execution on LambdaTest eCommerce Playground

Verification of expected text in URL on LambdaTest eCommerce Playground

Code Walkthrough:

Step 1: Firstly, it opens the web application using cy.visit().

Opening_web_application_with_cy visit

Step 2: Then, it asserts that the URL of the website is exactly equal to
https://ecommerce-playground.lambdatest.io/ using cy.url().should(‘eq’,
“https://ecommerce-playground.lambdatest.io/”)
.

Code walkthrough demonstrating URL assertion in Cypress testing

Step 3: In the end, use cy.url().should(‘include’, “https://ecommerce-playground”) asserts that the URL of the website includes the string https://ecommerce-playground.

Code snippet showing URL assertion in Cypress test

It is important to note that the above assertion doesn’t look for exact text. It checks if the passed text is present in the URL or not, whereas, in the first assertion, it tries to match the exact URL passed.

You need to choose it as per the requirement if the URL keeps updating based on the parameters. In those cases, include assertion cy.url().should(‘include’,URL) can be used, but if you have a fixed URL. you can directly use cy.url().should(‘eq’,URL).

Assert if the Element Is Not Present

If you want to verify if an element is not present on the page, you can use the Cypress .should(‘not.exist’) assertion. It is one of the most useful assertions when you want to verify the absence of an element on the page, such as when testing error messages, pop-up notifications, or elements that should be hidden or removed based on certain conditions.

In certain scenarios, a pop-up may appear on a web page when it is loaded, but it disappears after a certain period of time. In such cases, the Cypress .should(‘not.exist’) assertion proves to be extremely valuable as it allows you to verify the visibility of the pop-up.

For instance, consider a situation where a pop-up message is displayed upon page load, providing important information or updates to the user. After a brief moment, the pop-up disappears automatically. By using the Cypress .should(‘not.exist’) assertion, you can ensure that the pop-up is no longer present in the DOM, indicating that it has disappeared from the user’s view.

Syntax:

Assert if the Element Is Not Present

Test Scenario:

  1. Navigate to the LambdaTest eCommerce Playground website.
  2. Enter iphone in the search box.
  3. Verify search results do not have Samsung.

Implementation:

Test Execution:

LambdaTest eCommerce Playground website search for iPhone

Search results without Samsung products on LambdaTest eCommerce Playground

Code Walkthrough:

Step 1: The cy.visit() command is used to navigate to the specified URL.

code-walkthrough-step-1-cy-visit-command-navigating-to-specified-url

Step 2: In the below code, the cy.get() command selects the first input field with the placeholder text Search For Products and then types iphone.

screenshot-of-code-snippet-demonstrating-the-cy-get-command-selecting-the-first-input-field-with-the-placeholder-text-search-for-products-and-typing-iphone

Step 3: In the below code, it checks for text samsung in the dropdown and then verifies if samsung does not exist.

Code snippet showing a check for the text 'samsung' in a dropdown and verification of its non-existence

It is important to note that by adding Cypress .should(‘not.exist’) to any DOM command, Cypress will reverse its default assertion and automatically wait until the element does not exist.

For the cases where the element is present in the DOM but hidden from view, the Cypress .should(‘not.exist’) assertion will fail. In such cases, you may need to use other assertions, like visibility assertions, to handle elements that are hidden but still present in the DOM.

When leveraging the powerful Cypress .should() command, you can enhance your test automation by performing precise assertions, ensuring the desired behavior and quality of your application in the cloud-based testing environment.

AI-powered test orchestration and execution platforms like LambdaTest allow you to perform Cypress automation at scale on a remote test lab of 3000+ browsers and operating systems. You can further optimize and reduce your test execution time by harnessing the power of Cypress parallel testing.

Conclusion

Cypress UI automation framework offers a versatile and robust assertion method, .should(), that empowers you to perform a wide range of assertions based on various use cases. From verifying element visibility and content to examining attributes, CSS properties, URLs, and hash values, Cypress .should() provides a flexible and powerful approach to writing assertions. By leveraging this capability, you can enhance the quality and reliability of your web application by validating critical aspects and ensuring they meet the desired expectations.

Frequently Asked Questions (FAQs)

What is then() in Cypress?

In Cypress, the .then() method is used to handle the results of a previous command. It provides a way to modify and interact with the results of preceding commands, making your test code more readable and easier to maintain.

What is the use of should in Cypress?

The Cypress .should() command is used for conducting various types of assertions based on the current state or properties of an element. Additionally, it allows chaining multiple assertions together to perform more complex validations.

The command retries the assertion until it either passes or times out, making it suitable for waiting for specific conditions to be met. For example, it can be used to verify the status of a checkbox, such as whether it is checked or not, or to assert the value of an attribute or class of an element.

What are the Cypress commands?

Cypress offers a wide range of commands that make it easy to interact with web page elements, perform actions, and validate expectations. Some common Cypress commands include: .visit(), .go(), .reload(), and more.

Author Profile Author Profile Author Profile

Author’s Profile

Anshita Bhasin

Anshita Bhasin is a Senior QA Automation Engineer with over 9 years of experience in the software industry. Throughout her career, She has gained expertise in a variety of tools and technologies, including Rest Assured, Selenium, and Cypress. Currently, She is working at a PropTech company in Dubai. In addition to her technical expertise, she is also passionate about sharing her insights and experiences with others in the form of blogs and workshops to help guide those just starting out in their careers or seeking advice on their professional paths.

Blogs: 6



linkedintwitter

Test Your Web Or Mobile Apps On 3000+ Browsers

Signup for free