Test on Real Devices

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

Get Started free
Home Guide What are Cypress Assertions & How to Handle Them?

What are Cypress Assertions & How to Handle Them?

By Gurudatt S A, Community Contributor -

Tests are effective only when the outcome of the actions are validated against a set of expected results. Cypress provides assertion commands to validate the expected value with actual value and these assertion commands are from a popular library called Chai.

Cypress bundles the chai assertion library and there is no need to install this library.

The assertion involves passing two parameters to the command: expected values and actual values. The assertion command will check for a specific case and return a boolean value, which will then decide whether the test is passing or failing

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.

Below is an example which shows assertions in cypress

cy.get('.button')
  .should('exist')
  .and('be.visible')
  .and('have.class', 'active');

The example shows three assertions on a button

  • should(‘exist’): This will ensure the button exists in the DOM
  • and(‘be.visible’): This will ensure the button is visible in the DOM
  • and(‘have.class’, ‘active’): This will ensure the specified class name exists in the button

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.

Below is an example to explain implicit assertions in Cypress:

cy.get('input[name="firstName"]')

The get query command, by default, waits for the element to exist in the DOM and retries for the maximum timeout specified.

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.

Below is an example to explain explicit assertions in Cypress:

cy.get('input[name="firstName"]').should(“be.visible”)

The get query command, by default, waits for the element to exist. Using explicit assertions such as should(), it is possible to validate whether the element is visible. This approach allows for validating additional conditions on the element based on the test scenario, leading to more stable and reliable tests.

Types of Cypress Assertions

Cypress provides a robust set of assertion styles to validate application behavior during tests. These assertions help confirm that the application performs as expected by comparing actual outcomes with anticipated results.

  • BDD Assertion
  • TDD Assertion
  • Chai-jQuery

Learn More: 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

BrowserStack Automate Banner

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

Sinon-Chai Assertions in Cypress

The Chai assertion library provides support for Sinon.js assertions through the Sinon-Chai plugin. Sinon-Chai assertions are useful when using spies and stubs (spies are used for inspection, and stubs are used for mocking) in Cypress tests to validate conditions on the objects being spied on or stubbed.

Cypress by default comes with sinon-chai assertion installed.

Example:

describe('Example for sinon assertion', () => {
  it('validate the method is called on the spy object', () => {
    // Create a Sinon spy
    const logSpy = cy.spy(console, 'log');
    // Trigger the method
    console.log('Message from console');
    // Assert the spy was called
    expect(logSpy).to.be.calledOnce;
    expect(logSpy).to.be.calledWith('Message from console');
  });
});

In the example above, the method log, which is used for printing messages to the console, is being spied on:

const logSpy = cy.spy(console, 'log')

After the spy begins listening to the method’s invocation, the console.log method is called to print a message:

console.log('Message from console');

The number of times the console.log method was invoked and the message it was invoked with can then be asserted and verified.

expect(logSpy).to.be.calledOnce;
expect(logSpy).to.be.calledWith('Message from console');

Common Cypress Assertions

Below is the categorized summary of commonly used assertions

DOM Assertion:

cy.get(<selector>).should("be.visible")
cy.get(<selector>).should("have.class")
cy.get(<selector>).should("have.text")
cy.get(<selector>).should("not.be.visible")
cy.get(<selector>).should("be.checked")
cy.get(<selector>).should("have.value", "myValue")

API Assertion:

cy.request('/api/users')
  .its('body')

  .should('have.property', 'message')

  .and('be.an', 'array');

Spy/Stub Assertion:

expect(logSpy).to.be.called;
expect(logSpy).to.be.calledOnce;
expect(logSpy).to.be.calledWith('Check sinon case');

When Not to Assert in Cypress

While Cypress provides a comprehensive set of assertions, it is important to understand the implicit assertions that Cypress performs by default to avoid adding unnecessary explicit assertions.

To perform a click action in Cypress, the following code can be used:

cy.get("button").click()

In the above code

  • The get() command will check for the element to exist in DOM
  • The click command will wait for the button to become actionable.

With these built-in checks, there is no need to add explicit assertions for element existence or visibility, as they would be redundant.

Talk to an Expert

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

Automation Tests on Real Devices & Browsers

Seamlessly Run Automation Tests on 3500+ real Devices & Browsers