App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Home Guide What are Cypress Assertions? How to Handle it

What are Cypress Assertions? How to Handle it

By Gurudatt S A, Community Contributor -

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. 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 steps and outcomes of a test.

Steps:

  1. Open the browser
  2. 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. The tests should always end with an outcome assertion when writing automated tests. This article explores different types of Cypress Assertions and how to use them.

What are Cypress Assertions?

Cypress Assertions are essential in the Cypress testing framework and perfect for end-to-end testing. As per the official documentation, “Assertions describe the desired state of your elements, your objects, and your application.

  • By checking if certain conditions or expectations about your web page are met during a test, Cypress Assertions help you guarantee that your web app behaves correctly.
  • They ensure that your site’s crucial elements and interactions are functioning flawlessly.
  • Cypress comes bundled with a 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 is specified.

What are Implicit Assertions in Cypress?

Implicit assertions in Cypress are performed automatically without requiring an explicit assertion statement in the test code. These implicit assertions make tests more resilient by ensuring that elements are in the expected state before interacting with them.

What are Explicit Assertions in Cypress?

Explicit assertions give you fine-grained control over your test assertions and allow you to check specific conditions important for your test cases. You can use explicit assertions to check for specific conditions when writing tests in Cypress. Cypress provides a set of assertion commands for this purpose.

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

Examples of BDD Assertions

Examples of popular Cypress Assertions for certain scenarios are provided below:

ScenarioExample using should()Example using expect()
Asserting expected text/number equals to actual text/numbercy.get(“selector”).should(“have.text”, “AutomationTester”)expect(“expectedText”).to.have.text(“actualText”)
Asserting two objects with validating every property and its valuecy.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 valuecy.get(“selector”).invoke(“text”).should(“be.a”, “string”)expect(“value”).to.be.a(“string”)
Asserting expected value is greater than actual valuecy.get(“selector”).invoke(“text”).then(parseInt).should(“be.greaterThan”,20)expect(intValue).to.be.greaterThan(8)
Asserting length of elementscy.get(“selector”).should(“have.length”,3)expect(someValue).to.have.length(3)
Assert element is visiblecy.get(“selector”).should(“be.visible)expect(element).to.be.visible
Assert checkbox is checkedcy.get(“selector”).should(“be.checked”)expect(element).to.be.checked
Assert whether button is disabledcy.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 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.")
})

Examples of TDD Cypress Assertions

ScenarioExample
Assert if object is truthy(Ensures object is not undefined or null)assert.isOk(object, ‘Validate object is truthy’)
Assert if two objects are equalassert.equal(“0 Product(s) found.”, $el.text(), “Product Text found.”)
Assert if two objects are equal with all they keys are values are matchingassert.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 Objectassert.isObject({name: “user1, age: 26}, “Check if the value is object”)
Assert if the given value is greater than expected valueassert.isAbove(6,1, “Check if 6 is greater than 1”)
Assert if the given value belongs to a specific Data typeassert.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.")
})

Popular Chai-jQuery assertions in Cypress

ScenarioExample
Assert if attribute exists in the given elementexpect($el).to.have.attr(“href”, “/offers”)
Assert if element is visibleexpect($el).to.be.visible
Assert if element is enabledexpect($el).to.be.enabled
Assert if element contains partial textexpect($el).to.contain(“Favourite”)
Assert if the element checkbox is checkedexpect($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 works 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.
  • Cypress test automation can leverage the powerful cloud platform provided by BrowserStack Automate to run tests faster and more efficiently.

Run Cypress tests on Real Devices

Tags
Automated UI Testing Automation Testing Cypress

Featured Articles

Handling Alerts and Popups in Cypress

Handling Frames and iFrames in Cypress

Curated for all your Testing Needs

Actionable Insights, Tips, & Tutorials delivered in your Inbox
By subscribing , you agree to our Privacy Policy.
thank you illustration

Thank you for Subscribing!

Expect a curated list of guides shortly.