Handling Assertions in Cypress: Tutorial
By Gurudatt S A, Community Contributor - August 12, 2022
For every test, it is essential to have a validation that checks whether it functions as expected or not. Assertions are these validations in the test automation, which determine whether the test is working as expected or not. Based on these assertions, a test is marked as passed or failed depending on its successful functionality.
To understand assertion in detail, let us first go through what a test comprises: steps/actions and its outcome.
Let us take an example to understand the what are steps and outcomes of a test.
Steps:
- Open the browser
- Access BrowserStack demo website https://www.bstackdemo.com/
Outcome:
- BrowserStack demo website is loaded in the browser and displays the BrowserStack logo
Here, the outcome is the validation/assertion. When writing automated tests, the tests should always end with an outcome assertion. This article explores different types of Cypress Assertions and how to use them.
Quick Cheat Sheet on Handling Assertions in Cypress
Cypress comes bundled with a very popular assertion library Chai using which we can write powerful and effective assertions. The advantage of using Cypress Assertion is that it retries the previous chained command until defaultTimeout specified. As per the official documentation, “Assertions describe the desired state of your elements, your objects, and your application.”
Let’s discuss the different types of Cypress Asserts and their examples in detail below.
Types of Cypress Assertions
- BDD Assertion
- TDD Assertion
- Chai-jQuery
If you are new to Cypress, refer to this BrowserStack’s Cypress Documentation for initial setup
BDD Assertions in Cypress
BDD stands for Behavior-Driven Development, where the tests are written according to the User Behavior as Scenarios using Given, When, and Then.
Chai provides expect and should function to write assertions in a BDD way. Below are the examples of using expect() and should() assertions in Cypress.
Using expect
cy.visit("https://www.bstackdemo.com/") cy.get("#favourites strong").then(($el) => { expect($el.text()).to.be.eq("Favourites") })
Using should
cy.visit("https://www.bstackdemo.com/") cy.get("#favourites strong").invoke("text").should("be.eq", "Favourites")
Also Read: How to Run Tests with Cypress and Cucumber
Examples of popular Cypress Assertions for certain scenarios are provided below:
Scenario | Example using should() | Example using expect() |
---|---|---|
Asserting expected text/number equals to actual text/number | cy.get(“selector”).should(“have.text”, “AutomationTester”) | expect(“expectedText”).to.have.text(“actualText”) |
Asserting two objects with validating every property and its value | cy.get(someObject).should(“deep.equal”, {name: “AutomationTester”, age: 30}) | expect(someObject).to.deep.equal({name: “AutomationTester”, age: 30}) |
Asserting the data type of the actual value | cy.get(“selector”).invoke(“text”).should(“be.a”, “string”) | expect(“value”).to.be.a(“string”) |
Asserting expected value is greater than actual value | cy.get(“selector”).invoke(“text”).then(parseInt).should(“be.greaterThan”,20) | expect(intValue).to.be.greaterThan(8) |
Asserting length of elements | cy.get(“selector”).should(“have.length”,3) | expect(someValue).to.have.length(3) |
Assert element is visible | cy.get(“selector”).should(“be.visible) | expect(element).to.be.visible |
Assert checkbox is checked | cy.get(“selector”).should(“be.checked”) | expect(element).to.be.checked |
Assert whether button is disabled | cy.get(“selector”).should(“be.disabled”) | expect(element).to.be.disabled |
You can also add multiple assertions chained for better validation as seen in the command below
cy.get("selector").should("have.class","products-found").and("be.visible")
The complete list of Chai’s BDD assertion can be found here
TDD Assertions in Cypress
TDD Assertion is possible using assert static class, which is bundled inside Cypress.
Usage in Cypress is as below
cy.visit("https://www.bstackdemo.com/") cy.get(".products-found span").then(($el) => { assert.equal("0 Product(s) found.", $el.text(), "Product Text found.") })
Below are a few popular TDD Cypress assertions:
Scenario | Example |
---|---|
Assert if object is truthy(Ensures object is not undefined or null) | assert.isOk(object, ‘Validate object is truthy’) |
Assert if two objects are equal | assert.equal(“0 Product(s) found.”, $el.text(), “Product Text found.”) |
Assert if two objects are equal with all they keys are values are matching | assert.deepEqual({name: “User1”, Age: 26}, {name: “User1”, Age: “26”}), “This assertion will fail as the Age value in second object is string”) |
Assert if the given value is an Object | assert.isObject({name: “user1, age: 26}, “Check if the value is object”) |
Assert if the given value is greater than expected value | assert.isAbove(6,1, “Check if 6 is greater than 1”) |
Assert if the given value belongs to a specific Data type | assert.typeOf(“user1”, “string”, “Check if the value is of type string”) |
The complete list of Chai’s TDD assertion can be found here
Chai-jQuery Cypress Asserts
This assertion is helpful when we need to validate DOM elements and is usually used within the then() method of Cypress. This is because then() method will yield the jquery element.
Below is the example of using Chai-jQuery assertion in the Cypress test
cy.visit("https://www.bstackdemo.com/") cy.get(".products-found span").then(($el) => { expect($el).to.have.text("0 Product(s) found.") })
Here are a few popular Chai-jQuery assertions in Cypress:
Scenario | Example |
---|---|
Assert if attribute exists in the given element | expect($el).to.have.attr(“href”, “/offers”) |
Assert if element is visible | expect($el).to.be.visible |
Assert if element is enabled | expect($el).to.be.enabled |
Assert if element contains partial text | expect($el).to.contain(“Favourite”) |
Assert if the element checkbox is checked | expect($el).to.be.checked |
The complete list of Chai-jQuery assertions can be found here
Conclusion
In this article, you have seen the extensive assertion types that Cypress provides that can be used to write Cypress Automation tests with reliable validations. These Cypress Assertions will give enough confidence that a feature is working fine functionally without any issues.
Unlike other Test Automation tools, in Cypress, if you use the should() command for an assertion, this command will take care of retrying without adding any extra logic. This will reduce the flaky test percentage and provide stable tests.
As stable tests are critical, it is important to test the application on real device cloud for more accurate test results. By testing under real user conditions you can identify the bottlenecks in the real user experience and rectify them in time before release. Cypress test automation can leverage the powerful cloud platform provided by BrowserStack Automate to run tests faster and more efficiently.