Cypress .should() Command: A Detailed Guide
Anshita Bhasin
Posted On: May 7, 2024
113567 Views
30 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:
Here are some examples that demonstrate the usage of the Cypress .should() command with cy.get(), cy.contains(), and cy.wrap():
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)
|
.then(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:
It can be used with Document Object Model (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:
|
Implementation:
Below is the Cypress code to open the web application and verify the class using the Cypress .should(‘have.class’,className) assertion.
1 2 3 4 5 6 7 |
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') }) }) |
Test 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 the Cypress .should() command, the same class name is passed along with the locator of the element on the web page.
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.
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.
Syntax:
Let’s understand in detail with a test scenario.
Test Scenario:
|
Implementation:
1 2 3 4 5 6 7 8 |
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) }) }) |
Test 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 screenshot below, 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).
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:
Test Scenario:
|
Implementation:
1 2 3 4 5 6 |
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') }) }) |
Test 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, or 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 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.
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.
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:
Let’s understand it with the below examples.
Test Scenarios:
|
|
Implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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') }) }) |
Test 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: The 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.
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:
Let’s understand with below test scenario:
Test Scenario:
|
Implementation:
1 2 3 4 5 6 |
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') }) }) |
Test Execution:
Code Walkthrough:
Step 1: In the first step, the cy.visit() command is used to navigate to the 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.
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.
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:
Let’s understand in detail how to write assertions for checkboxes using Cypress using the below scenario.
Test Scenario:
|
Implementation:
1 2 3 4 5 6 7 8 9 10 |
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') }) }) |
Test Execution:
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.
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.
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.
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
|
Test Case 2
Navigate to the Dropdown Demo page of Selenium Playground. |
Implementation:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
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') }) }) |
Test Execution:
Code Walkthrough:
Test Case 1
Step 1: The cy.visit() command is used to navigate to the 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.
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: The cy.visit() command is used to navigate to the specified URL.
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.
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:
Let’s understand the below test scenario.
Test Scenario:
|
Implementation:
1 2 3 4 5 6 |
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'); }) }) |
Test Execution
Code Walkthrough:
Step 1: The cy.visit() command is used to navigate to the 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.
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.
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:
Test Scenario:
|
Implementation:
1 2 3 4 5 6 |
describe('Cypress Assertions', () => { it.only('Should - Empty Assertion', () => { cy.visit('https://ecommerce-playground.lambdatest.io/') cy.hash().should('be.empty') }) }) |
Test Execution:
Code Walkthrough:
Step 1: The cy.visit() command is used to navigate to the specified 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.
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:
Test Scenario:
|
Implementation:
Test 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 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:
|
Implementation:
1 2 3 4 5 6 7 |
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') }) }) |
Test Execution:
Code Walkthrough:
Step 1: The cy.visit() command is used to navigate to the 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.
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.
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.
Run your Cypress tests across 53+ browser versions on the cloud. Try LambdaTest Now!
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.
Got Questions? Drop them on LambdaTest Community. Visit now