Cypress .should() Command: A Detailed Guide
Tags: webdev, testing, cypress, tutorial
Published: 2023-06-27 08:20:31




An assertion is a way to validate that the application or system under test is functioning as expected. In [Cypress](https://www.lambdatest.com/learning-hub/cypress-tutorial?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub), 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](https://www.lambdatest.com/learning-hub/cypress-tutorial/?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub), 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](https://www.lambdatest.com/learning-hub/test-execution?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub). 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](https://www.lambdatest.com/learning-hub/cypress-assertions?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub).

{% youtube jI7hDyLESvg %}

**_Here's Top 30+ [WebdriverIO Interview Questions](https://www.lambdatest.com/learning-hub/webdriverio-interview-questions?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub) 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**

![](https://cdn-images-1.medium.com/max/2000/0*c3qTqmuafy4OiW7r.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*uVxcqWl-81bLlRKw.png)

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](https://www.lambdatest.com/learning-hub/jest-interview-questions?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub) 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**

![](https://cdn-images-1.medium.com/max/2000/0*j1c9_kze_nu8DmCQ.png)

It can be used with [DOM](https://www.lambdatest.com/blog/document-object-model/) commands like *cy.get(), cy.contains(), or cy.wrap(),* as shown below:

![](https://cdn-images-1.medium.com/max/2000/0*GlA_lw1aAEUKKLC7.png)

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/](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')
       })
    })
```

**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*hbP8sNiI7Jka2xLU.png)

![](https://cdn-images-1.medium.com/max/2592/0*59EkM0jfVQ74aGtp.png)

**Code Walkthrough**

**Step 1**

Firstly, the test navigates to the URL of the website using *cy.visit()*.

![](https://cdn-images-1.medium.com/max/2350/0*QBYykX0fwryQMq5e.png)

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

![](https://cdn-images-1.medium.com/max/2348/0*UTEc_-5Wl9ut3sas.png)

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

![](https://cdn-images-1.medium.com/max/3200/0*w8M1Du-OpXPiQw9v.png)

**Step 4**

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

![](https://cdn-images-1.medium.com/max/2000/0*Yrstecjs7hUISfJT.png)

**Step 5**

The last line selects the login button on the page using a [CSS Selector](https://www.lambdatest.com/learning-hub/css-selectors?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub) and then checks that it has the classes *btn *and *btn-primary*.

![](https://cdn-images-1.medium.com/max/2000/0*tfZEX2HzgzBi9jlW.png)

![](https://cdn-images-1.medium.com/max/3200/0*wnMKhqB6ExbFlt5w.png)

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](https://www.lambdatest.com/learning-hub/mocha-interview-questions?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub) 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.

![](https://cdn-images-1.medium.com/max/3200/0*e_xW40WNYOz_O2Ad.png)

**Syntax**

![](https://cdn-images-1.medium.com/max/2000/0*7MLiYZYE0lf_gfB5.png)

Let’s understand in detail with a test scenario.

**Test Scenario**

 1. Navigate to the [https://ecommerce-playground.lambdatest.io/](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)
       })  })
```

**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*kFAMc3Zmmwd2jxl0.png)

![](https://cdn-images-1.medium.com/max/2828/0*3FJZZHWIsKriBrcA.png)

**Code Walkthrough**

**Step 1**

Firstly, the test navigates to the URL of the website using *cy.visit()*.

![](https://cdn-images-1.medium.com/max/3200/0*8Qs8ybHb9Qg0TDqe.png)

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

![](https://cdn-images-1.medium.com/max/3200/0*kW02FEVv3hD3qdmq.png)

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

![](https://cdn-images-1.medium.com/max/3200/0*C1ltwXedKRlQTrs5.png)

![](https://cdn-images-1.medium.com/max/3200/0*KPfnvJvCOa1FQecN.png)

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

![](https://cdn-images-1.medium.com/max/3200/0*41cp_Z0FcAzQEvU5.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*PiUn_oLeq5e1p2JF.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*KTFph34_FYgGTw6M.png)

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

![](https://cdn-images-1.medium.com/max/3200/0*bi2fl9aJuVR-0CUH.png)

**_Boost your testing skills with [Pytest interview questions](https://www.lambdatest.com/learning-hub/pytest-interview-questions?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub). 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**

![](https://cdn-images-1.medium.com/max/2980/0*9Wl94gqGCV2cdGlm.png)

**Test Scenario**

 1. Navigate to the website [https://ecommerce-playground.lambdatest.io/](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')
       }) })

```
**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*-ypbdBqyMWrPU22-.png)

![](https://cdn-images-1.medium.com/max/2750/0*u7vdneiY7X8REG6K.png)

**Code Walkthrough**

**Step 1**

Firstly, the test navigates to the URL of the website using *cy.visit()*.

![](https://cdn-images-1.medium.com/max/3200/0*b2tr7HGBxWQPqDLn.png)

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

![](https://cdn-images-1.medium.com/max/3200/0*Gdtz1KEJYgqVqMhv.png)

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.

![](https://cdn-images-1.medium.com/max/3200/0*EhikCn7UX2dqyLZs.png)

![](https://cdn-images-1.medium.com/max/2610/0*Uou0qPumB4_Ii7Pz.png)

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

![](https://cdn-images-1.medium.com/max/3200/0*pzybU_bgb1nIUrCt.png)

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.

![](https://cdn-images-1.medium.com/max/3200/0*oJmLg4btAecjAN_w.png)

![](https://cdn-images-1.medium.com/max/3200/0*5KlAXvvnWCAEA3DP.png)

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](https://www.lambdatest.com/learning-hub/specflow-interview-questions?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub) 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**

![](https://cdn-images-1.medium.com/max/3200/0*1L_YNawbuNwiV5Va.png)

Let’s understand it with the below examples.

**Test Scenarios**

**Test Case 1**

 1. Navigate to URL [https://ecommerce-playground.lambdatest.io/](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](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')
       })
    })

```
**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*srHli1XI497LoUhX.png)

![](https://cdn-images-1.medium.com/max/2318/0*xToSL3Ef0DkE2Vkt.png)

![](https://cdn-images-1.medium.com/max/3200/0*04dFm0lw03U_bY8A.png)

![](https://cdn-images-1.medium.com/max/3200/0*WZGK5dlGLNYuUa4w.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*BNJYcP18OUdsws4z.png)

**Step 2**

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

![](https://cdn-images-1.medium.com/max/2000/0*vfeAWf2ytOTXt_Yy.png)

**Step 3**

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

![](https://cdn-images-1.medium.com/max/2000/0*x9RMQovJGg9FDfu8.png)

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

![](https://cdn-images-1.medium.com/max/2204/0*dezEGKJHQFYq2Chx.png)

**Step 2**

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

![](https://cdn-images-1.medium.com/max/2000/0*G6y02axoZD8NWmhG.png)

**Step 3**

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

![](https://cdn-images-1.medium.com/max/2050/0*kBnn0yPFjt3_89_z.png)

**_Here's Top 30 [Robot Framework Interview Questions](https://www.lambdatest.com/learning-hub/robot-framework-interview-questions?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub) 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**

![](https://cdn-images-1.medium.com/max/2082/0*b6jPfXL_kC4kruzc.png)

Let’s understand with below test scenario:

**Test Scenario**

 1. Navigate to the URL [https://ecommerce-playground.lambdatest.io/](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')
           })
    })
```

**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*DNkYAU9t8_AmFuNE.png)

![](https://cdn-images-1.medium.com/max/3004/0*D5cdVd60Q50FsleJ.png)

**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/](https://ecommerce-playground.lambdatest.io/).

![](https://cdn-images-1.medium.com/max/2000/0*h72-eE2HJdr7MI4v.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*lIBz8JrcwqQw_DT2.png)

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.

![](https://cdn-images-1.medium.com/max/2000/0*2zsFZOUgG5ZIziVz.png)

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](https://ecommerce-playground.lambdatest.io/index.php?route=common/home).

![](https://cdn-images-1.medium.com/max/2000/0*bw47JLEhNO7GPqUR.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*7cQyHXmDxglvKVdz.png)

**_In this tutorial, learn what is [Regression testing](https://www.lambdatest.com/learning-hub/regression-testing?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=learning_hub), 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**

![](https://cdn-images-1.medium.com/max/2000/0*Ppp9p-b_7NvDDC_W.png)

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](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')
       })
    })

```
**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*mrquHyv3sK3l66yd.png)

![](https://cdn-images-1.medium.com/max/2330/0*Xig9ZO9aaH_5A4hO.png)

**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.](https://www.lambdatest.com/selenium-playground/checkbox-demo)

![](https://cdn-images-1.medium.com/max/2052/0*4dwchq1G9MDdm_A8.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*wyMCfoVyY6gc30uX.png)

![](https://cdn-images-1.medium.com/max/2000/0*YxtpsKmBC-Wh7bPJ.png)

![](https://cdn-images-1.medium.com/max/3072/0*dTZ-M_UrVlIDgIZt.png)

![](https://cdn-images-1.medium.com/max/3200/0*TUDNto3sg0_b4ZMK.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*cx8duPX-NaYjDOD9.png)

**_Run your [Selenium Automation Testing](https://www.lambdatest.com/selenium-automation?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) 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.](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.](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')
       })
    })

```
**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*L96gVglkj1R6rEtu.png)

![](https://cdn-images-1.medium.com/max/3200/0*aYLDh0uXXbrhg6D3.png)

![](https://cdn-images-1.medium.com/max/2000/0*HOAEOlTiLetpWYUC.png)

**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/.](https://ecommerce-playground.lambdatest.io/)

![](https://cdn-images-1.medium.com/max/2000/0*BAoqXqNBSWbkRGJZ.png)

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

![](https://cdn-images-1.medium.com/max/2106/0*VPKLt20oob5PstRR.png)

![](https://cdn-images-1.medium.com/max/2600/0*DQgITwgre1Q-0eRI.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*urNXD9hFr6-TxpMN.png)

![](https://cdn-images-1.medium.com/max/2600/0*io7juf4BMTZBnCwc.png)

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.

![](https://cdn-images-1.medium.com/max/2000/0*VPeEcN6hgDV0xjte.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*1U8ZSDCshkcoDpdk.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*U-g1ex0L9cPt-vQ4.png)

**Test Case 2**

**Step 1**

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

![](https://cdn-images-1.medium.com/max/2238/0*1ptVEfPRM1fI01qo.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*rfdZyEBTdQNl8eGA.png)

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

![](https://cdn-images-1.medium.com/max/2532/0*tv633CnxdebOZo6p.png)

**_Do you need to gather more knowledge on [website testing](https://www.lambdatest.com/blog/website-testing/?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=blog)? 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**

![](https://cdn-images-1.medium.com/max/2000/0*HiC8FNOBQP14UHEL.png)

Let’s understand the below test scenario.

**Test Scenario**

 1. Navigate to the URL [https://ecommerce-playground.lambdatest.io/](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');
           }) })
```

**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*YvEMyjCtZWTGXWkB.png)

![](https://cdn-images-1.medium.com/max/3200/0*XLdvP7aH9VSDj9KE.png)

**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/](https://ecommerce-playground.lambdatest.io/)

![](https://cdn-images-1.medium.com/max/2000/0*to2TQsFvnsYBjITv.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*ONuVV8FIYdEmdBjb.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*adfiJ_BeBQf0xW5w.png)

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](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) 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**

![](https://cdn-images-1.medium.com/max/2000/0*PBF8gHxUa46c_F8C.png)

**Test Scenario**

 1. Navigate to the URL [https://ecommerce-playground.lambdatest.io/](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')
       })
    })
```

**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*lrSM1GpM-fGM6sRb.png)

![](https://cdn-images-1.medium.com/max/3200/0*7uyM1rh9yLPtJJnR.png)

![](https://cdn-images-1.medium.com/max/2524/0*RbSkcQXTS0-RNExC.png)

**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/](https://ecommerce-playground.lambdatest.io/).

![](https://cdn-images-1.medium.com/max/2000/0*ir5w91W3XsK1K4pa.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*rI9mfxHbGe2Aup1r.png)

**_This tutorial dive deep into [web testing](https://www.lambdatest.com/learning-hub/web-testing?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) 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**

![](https://cdn-images-1.medium.com/max/2000/0*M0b4smImd1yPPNFZ.png)

**Test Scenario**

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

![](https://cdn-images-1.medium.com/max/2000/0*deqM4IzUUbjmQ5Br.png)

**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*SYuL10LTTL6BHV8T.png)

![](https://cdn-images-1.medium.com/max/3024/0*BFZznfIejFv0nOgj.png)

![](https://cdn-images-1.medium.com/max/3186/0*cQztAHtchxtXjry0.png)

**Code Walkthrough**

**Step 1**

Firstly, it opens the web application using *cy.visit()*.

![](https://cdn-images-1.medium.com/max/2000/0*3Md-oRrAqbJtqAHa.png)

**Step 2**

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

![](https://cdn-images-1.medium.com/max/3200/0*WcbwUS44dMOi0s7a.png)

**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](https://ecommerce-playground.lambdatest.io/)”.

![](https://cdn-images-1.medium.com/max/2000/0*GKYfYB6vuzyqL7D-.png)

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

![](https://cdn-images-1.medium.com/max/2000/0*4-cE2PjT7h8WYgjS.png)

**Test Scenario**

 1. Navigate to the URL [https://ecommerce-playground.lambdatest.io/](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')
    
    
       })
    })
```

**Execution**

![](https://cdn-images-1.medium.com/max/3200/0*eih2hSslzasrs9O4.png)

![](https://cdn-images-1.medium.com/max/2400/0*dcPusvQ3c_f_aAXf.png)

**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/](https://ecommerce-playground.lambdatest.io/).

![](https://cdn-images-1.medium.com/max/2000/0*mTFyE2LBUOD44URC.png)

**Step 2**

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

![](https://cdn-images-1.medium.com/max/2000/0*IcYIj0xUdxBkgfdW.png)

**Step 3**

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

![](https://cdn-images-1.medium.com/max/2000/0*z6-4UQ-pvY63SvUU.png)

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](https://www.lambdatest.com/automation-testing?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) 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](https://www.lambdatest.com/blog/cypress-test-automation-framework/?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=blog) at scale over an [online browser farm](https://www.lambdatest.com/online-browser-farm?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) of 3000+ browsers and operating systems. You can further optimize and reduce your test execution time by harnessing the power of [Cypress parallel testing](https://www.lambdatest.com/cypress-parallel-testing?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage).


{% youtube jX3v3N6oN5M %}

**_Test native, hybrid, and web apps on any mobile OS with our free [Android emulator](https://www.lambdatest.com/android-emulator-online?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) online. Sign up to optimize app performance._**

**Note:** Here is our support documentation to help you [get started with Cypress testing](https://www.lambdatest.com/support/docs/getting-started-with-cypress-testing/?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage)

Are you ready to elevate your Cypress automation skills? Join our specialized [Cypress 101 certification](https://www.lambdatest.com/certifications/cypress-101?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) course, tailored for developers and testers seeking to expand their expertise in [Cypress test automation](https://www.lambdatest.com/blog/cypress-test-automation-framework/?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=blog). Gain advanced knowledge and sharpen your skills to unlock new possibilities in your test automation journey.

## Conclusion

[Cypress UI automation](https://www.lambdatest.com/cypress-ui-automation?utm_source=devto&utm_medium=organic&utm_campaign=jun27_kj&utm_term=kj&utm_content=webpage) 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.