DEV Community

Cover image for Cypress .should() Command: A Detailed Guide
BhasinAnshita for LambdaTest

Posted on • Originally published at lambdatest.com

Cypress .should() Command: A Detailed Guide

An assertion is a way to validate that the application or system under test is functioning as expected. In Cypress, assertions are used to ensure that the state of the application being tested meets the anticipated conditions.

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, I will explain in detail about using Cypress .should() command along with some real time use cases.
_

Quick Recap: 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 results of the Application Under Test (AUT) do not align with the expected outcome, it is crucial to report any discrepancies as bugs. This practice plays a vital role in upholding the reliability and quality of the application.

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

Here's Top 30+ WebdriverIO Interview Questions and Answers that will help you boost your confidence in an Interview.

What is the use of 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 is used to ensure 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. This makes tests more resilient to flakiness caused by timing issues or network latency.

Syntax

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

In this blog, I will be using cy.get() for .should() assertion.

Assertion can be handled in different ways. Below are the most commonly used ways you can handle assertion in Cypress.

  • Assert based on class value

  • Assert based on length

  • Assert based on text

  • Assert based on 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

Let’s understand in detail:

Prepare to ace your Jest interview questions with our thorough set of interview questions and solutions that will enable you to prove your command of the Jest testing framework.

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 utilized 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

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

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

Test Scenario

  1. Navigate to URL https://ecommerce-playground.lambdatest.io/ using cy.visit().

  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.

 describe('Cypress Assertions', () => {
       it('Should - Class Assertion', () => {
           cy.visit(' https://ecommerce-playground.lambdatest.io/')   cy.get('#input-email').type('lambdatest.Cypress@disposable.com').should('have.class', 'form-control')
           cy.get('#input-password').type('Cypress123!!')
           cy.get('[value="Login"]').should('have.class', 'btn btn-primary')
       })
    })
Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Step 1

Firstly, the test 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.

Step 3

As shown in the screenshot below, the class name of the locator is “form-control” in DOM. So, in Cypress .should(), the same class name is passed along with the locator of the element on the webpage.

Step 4

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

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.

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

Get ready for your Mocha interview with our expert-curated list of Mocha interview questions tips. Impress your potential employer and land your dream job!

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 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.

Syntax

Let’s understand in detail with a test scenario.

Test Scenario

  1. Navigate to the https://ecommerce-playground.lambdatest.io/ 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

describe('Cypress Assertions', () => {
       it('Should - Length Assertion', () => {
           /* Verify the number of categories on the page */
           cy.visit('https://ecommerce-playground.lambdatest.io/')
           cy.get('.navbar-nav.horizontal>li').should('have.length', 6)
           /* Verify the number of top products on the page */
           cy.get('.swiper-wrapper').eq(1).find('>div').should('have.length, 10)
       })  })
Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Step 1

Firstly, the test 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’.

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

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‘.

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

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’).

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).

Boost your testing skills with Pytest interview questions. Beginner, intermediate, and advanced levels covered. Prepare and excel in your interviews.!

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 webpage. 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

Test Scenario

  1. Navigate to the website https://ecommerce-playground.lambdatest.io/.

  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

describe('Cypress Assertions', () => {
       it('Should - Text Assertion', () => {
           /* Verify the text of category on the page */
           cy.visit('https://ecommerce-playground.lambdatest.io/')    cy.get('.m-md-0.d-flex.align-items-center.mb-3').should('have.text', "Upto 30% Off on Popular Smartphones + Exchange Offers")
           /* Verify the text of specific products at specific location on the page */    cy.get('.swiper-slide.swiper-slide-active').eq(2).find('>div>div>h4>a').first().should('have.text', 'HTC Touch HD')
       }) })

Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Step 1

Firstly, the test 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”.

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 else your test case will fail. Even if there is space in the text, the test case will fail in that case.

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 specific 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.

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

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.

Ace your QA interviews with our comprehensive guide on 60+ SpecFlow Interview Questions and Answers. Boost your BDD knowledge and showcase your SpecFlow expertise.

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

Let’s understand it with the below examples.

Test Scenarios

Test Case 1

  1. Navigate to URL https://ecommerce-playground.lambdatest.io/ 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.

Test Case 2

  1. Navigate to URL https://www.lambdatest.com/selenium-playground/select-dropdown-demo.

  2. Select the dropdown value.

  3. Verify the selected dropdown value is as expected.

Implementation

describe('Cypress Assertions', () => {
       it.only('Should - Value Assertion for Textbox', () => {
           cy.visit('https://ecommerce-playground.lambdatest.io/')
           cy.get('input[name="search"]').first().type('iphone')
           cy.get('input[name="search"]').first().should('have.value', 'iphone')
          cy.get('input[name="search"]').first().should('not.have.value', 'IPHONE')


       })


       it('Should - Value Assertion for Dropdown', () => {
    cy.visit('https://www.lambdatest.com/selenium-playground/select-dropdown-demo')
           cy.get('#select-demo').select('Wednesday')
           cy.get('#select-demo option:selected').should('have.value', 'Wednesday')
       })
    })

Enter fullscreen mode Exit fullscreen mode

Execution

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().

Step 2

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

Step 3

After entering the text in the textbox, it verifies if the entered text matches the expected 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

First step is to 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.

Step 3

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

Here's Top 30 Robot Framework Interview Questions and Answers that will help you boost your confidence in an Interview.

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 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

Let’s understand with below test scenario:

Test Scenario

  1. Navigate to the URL https://ecommerce-playground.lambdatest.io/.

  2. Select dropdown value.

  3. Verify the selected dropdown value is as expected.

Implementation

 describe('Cypress Assertions', () => {


       it.only('Should - Attribute Assertion for Textbox', () => {
           cy.visit('https://ecommerce-playground.lambdatest.io/')
           cy.get('span:contains("Home")').parents('a').should('have.attr', 'href','https://ecommerce-playground.lambdatest.io/index.php?route=common/home')
           })
    })
Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Step 1

In the first step, the cy.visit() command is used to navigate to the specified URL, which is https://ecommerce-playground.lambdatest.io/.

Step 2

I am using the cy.get() command to select the element on the web page containing the text “Home“, which in this case is a span element.

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.

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.

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

In this tutorial, learn what is Regression testing, its importance, types, and how to perform it.

Assert for checkboxes

When it comes to testing forms, checkboxes are a common element to 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

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

Test Scenario

  1. Navigate to URL https://www.lambdatest.com/selenium-playground/checkbox-demo.

  2. Select a single checkbox and validate if it got checked.

  3. Select multiple checkboxes on the page.

  4. Verify all the checkboxes got selected/checked.

  5. Uncheck the single checkbox and verify it got unchecked.

  6. Uncheck the multiple checkboxes and verify if they got unchecked.

Implementation


    describe('Cypress Assertions', () => {
       it('Should - Checkbox Assertion', () => {   cy.visit('https://www.lambdatest.com/selenium-playground/checkbox-demo')
           /* select checkbox and verify if it is checked */
           cy.get('#isAgeSelected').check().should('be.checked')
           cy.get('.cb-element.mr-10').check().should('be.checked')
           /* unselect checkbox and verify if it is unchecked */
           cy.get('#isAgeSelected').uncheck().should('not.be.checked')
           cy.get('.cb-element.mr-10').uncheck().should('not.be.checked')
       })
    })

Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

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

Step 1

Using the below code, the cy.visit() command is used to navigate to the specified URL, which is https://www.lambdatest.com/selenium-playground/checkbox-demo.

Step 2

As shown in the below screenshot, I am using the cy.get() command to select the element on the webpage along with the .check() command, which is used to select the checkbox. Then, Cypress .should(‘be.checked’) command is used to assert that the checkboxes are checked.

Step 3

In the below code, I am using the cy.get() command to select the element on the webpage 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.

Run your Selenium Automation Testing scripts on the LambdaTest cloud grid. Test on 3000+ desktop & mobile environments. Try it for free!

Chaining Multiple Assertions using Cypress .should() Command

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

Let’s understand in detail why Chaining is used:

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 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 URL https://www.lambdatest.com/selenium-playground/checkbox-demo.

  2. Verify Top Trending Category products on the page are 8 in the count and verify the last element is “MP3 Players” and has CSS “font-family”

  3. Verify search box has the attribute aria-label has the value “Search For Products”.

  4. Enter the text in the search box and verify the entered text is as expected.

Test Case 2

  1. Navigate to URL https://www.lambdatest.com/selenium-playground/select-dropdown-demo.

  2. 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

describe('Cypress Assertions', () => {
       it('Should - Multiple Assertion', () => {
           cy.visit('https://ecommerce-playground.lambdatest.io/')
           cy.get('.figure.img-top').should('have.length', 8)
               .last()
               .should('include.text', "MP3 Players").should('have.css', 'font-family')
           cy.get('input[name="search"]').first().should('have.attr', 'aria-label', "Search For Products").type('iphone').should('have.value', 'iphone')
       })
       it('Should - Multiple Assertion for Dropdown', () => {    cy.visit('https://www.lambdatest.com/selenium-playground/select-dropdown-demo')
           cy.get('#select-demo').select('Wednesday')
           cy.get('#select-demo option:selected').should('be.selected').and('have.value', 'Wednesday')
       })
    })

Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Test Case 1

Step 1

Using the below code, the cy.visit() command is used to navigate to the specified URL, which is https://ecommerce-playground.lambdatest.io/.

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“.

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”.

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.

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“.

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“.

Test Case 2

Step 1

First, I am navigating to the specified URL, which is https://www.lambdatest.com/selenium-playground/select-dropdown-demo using cy.visit().

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“.

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.

Do you need to gather more knowledge on website testing? LambdaTest is here to explain further.

Assert if the text is visible/hidden

To verify if the DOM element is visible on the page. In Cypress, .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 is the same, which was entered while registering. 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 does not exist on the page. For example, if you want to verify the error text on the page does not exist. In that case, you can use the Cypress .should(‘not.be.visible’) command.

Syntax

Let’s understand the below test scenario.

Test Scenario

  1. Navigate to the URL https://ecommerce-playground.lambdatest.io/.

  2. Verify on the web page that the category “Home” is visible.

  3. Verify if a modal dialog is hidden on the page.

Implementation

 describe('Cypress Assertions', () => {
       it.only('Should - Visibility Assertion', () => {
           cy.visit('https://ecommerce-playground.lambdatest.io/')
           cy.get('span:contains("Home")').should('be.visible')
           cy.get('.modal-dialog').should('not.be.visible');
           }) })
Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Step 1

Using the below code, the cy.visit() command is used to navigate to the specified URL, which is https://ecommerce-playground.lambdatest.io/

Step 2

As per the code in the below screenshot, I am using the cy.get() command 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.

Step 3

As per the code in the below screenshot, I am using the cy.get().should(‘not.be.visible’) command 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.

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.

Perform browser automation testing on the most powerful cloud infrastructure. Leverage LambdaTest automation testing for faster, reliable and scalable experience on cloud.

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

  • Verifying Empty Lists or Tables

  • Testing Empty Input Fields

Syntax

Test Scenario

  1. Navigate to the URL https://ecommerce-playground.lambdatest.io/.

  2. Verify the URL hash is being used correctly.

Implementation

describe('Cypress Assertions', () => {


       it.only('Should - Empty Assertion', () => {
           cy.visit('https://ecommerce-playground.lambdatest.io/')
           cy.hash().should('be.empty')
       })
    })
Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Step 1

Using the below code, the cy.visit() command is used to navigate to the specified URL, which is https://ecommerce-playground.lambdatest.io/.

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.

This tutorial dive deep into web testing to help you understand its life cycle, elements, angles, the role of automation, and more.

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() assertion, 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().

Syntax

Test Scenario

  1. Navigate to the URL https://ecommerce-playground.lambdatest.io/.

  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

Execution

Code Walkthrough

Step 1

Firstly, it opens the web application using 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/”)
.

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”.

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 and my personal favorite ,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

Test Scenario

  1. Navigate to the URL https://ecommerce-playground.lambdatest.io/.

  2. Enter Iphone in the search box.

  3. Verify search results do not have “Samsung”.

Implementation

 describe('Cypress Assertions', () => {


       it('Should - Multiple Assertion', () => {
           cy.visit('https://ecommerce-playground.lambdatest.io/')
           cy.get('[placeholder="Search For Products"]').first().type('iphone')
           cy.get('.dropdown-menu.autocomplete.w-100').contains('samsung').should('not.exist')


       })
    })
Enter fullscreen mode Exit fullscreen mode

Execution

Code Walkthrough

Step 1

Using the below code, the cy.visit() command is used to navigate to the specified URL, which is https://ecommerce-playground.lambdatest.io/.

Step 2

In the below code, it selects the first input field with the placeholder text Search For Products and then types iphone.

Step 3

In the below code, it checks for text Samsung in the dropdown and then verifies if Samsung does not exist.

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.

Cloud testing platforms like LambdaTest allow you to perform Cypress automation at scale over an online browser farm of 3000+ browsers and operating systems. You can further optimize and reduce your test execution time by harnessing the power of Cypress parallel testing.

Test native, hybrid, and web apps on any mobile OS with our free Android emulator online. Sign up to optimize app performance.

Note: Here is our support documentation to help you get started with Cypress testing

Are you ready to elevate your Cypress automation skills? Join our specialized Cypress 101 certification course, tailored for developers and testers seeking to expand their expertise in Cypress test automation. Gain advanced knowledge and sharpen your skills to unlock new possibilities in your test automation journey.

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.

Top comments (0)