Cypress Assertions – Complete Guide with Examples

Cypress assertions

Summarize this blog post with:

Cypress Assertions: First, we will try to understand what exactly Cypress is. And why is it used?

So, Cypress is a new-age test automation tool used for Web application automation, where we can validate different UI checks and screens of an application. Cypress speeds up the execution as compared to performing this manually. When we perform Web application testing manually, we tend to miss attention to detail, whereas with Cypress, we get all the test cases formed in the form of scripts, and it covers everything in detail.

Cypress is just like a robot who works on instructions given by a test developer using a scripting language. It clicks on buttons, links, and fetches data from the UI for further validation. By providing a set of instructions to Cypress, we can navigate through the website and test all possible scenarios, both positive and negative.

Also Read: Check if an element exists or not using Cypress

While executing the test, Cypress works in two ways: headed and headless. When we give commands for headed execution, you will see a new window open with options for selecting web browsers. From there, you can select Chrome or Electron and kick off your automation run. Whereas when we perform execution in headless mode, we start the execution by defining @tags, which will help Cypress to understand which test cases need to be executed and which can be skipped.

We can define Cypress framework using cucumber, we can create feature files which will have all the test steps defined in Gherkins and for each step there will be step definition, we will be having a POM (Page object model) using that we will keep all page-related identifiers at one place . Inside the Fixture folder, we will be keeping all our test data, we will keep general utilities in the Utility folder, which will be called out in step definitions. For reporting, we can use the allure report or the HTML report.

For this article, we are targeting to understand Cypress assertions, so first, we will try to understand:

What Are Assertions in Cypress?

In general, English “a statement that says you strongly believe that something is true,”’, so for implementing this in Cypress, we have two libraries, “Chai” and “Jest”. Using these libraries, we can access multiple methods which we can use values and behaviour of the program or code.

Assertions usually evaluate in boolean format in “True” or “False”, based on which we make a decision if the test case is passing or failed or sometimes we define other flows based on the outputs that we are getting from assertions. If we do not use assertions in the code, it will become very difficult to identify the problem, plus validate the functionality that should be there in the application. If we are expecting a button to be there on the UI and it should be enabled, then we will need assertions.

In Cypress, we have Chai Library, which helps in providing multiple assertion functions, including “Should” and “expect,” which are the two most commonly used assertion functions.

In the following sections, we will explore the different types of Cypress asserts and provide examples of each.

Types of Cypress Assertions

Behavior-Driven (BDD) Assertions in Cypress

BDD (Behaviour-driven development) is written with Keywords such as Given/When/Then/And, which define the expected behaviour in very easy and understandable language. We use Should and expect functions for implementing these assertions.

1. “.should()”:

The `.should()` command is used to make various assertions about elements on the page. We will be providing a string argument describing the condition we are checking and a chaining function that specifies the assertion. We can have multiple “should” assertions chained together for validating complex functionality and other aspects of the web application.

cy.get('button').should('be.visible');  // Checks if the button is visible
cy.get('input').should('have.value', 'Hello');  // Checks if the input has the value "Hello"

cy.get("#element").should("have.class", "some-class"); // Checks if element has a specific class

cy.get("#element").should("be.hidden"); //Checks if element is hidden

Real-time example:

When("I select {string} option from {string} dropdown", (option, placeholder) => {
  cy.get(`input[placeholder="${placeholder}"]`)
    .click()
    .then(() => {
      cy.get("li").contains(option).click();
    })
    .then(() => {
      cy.get(`input[value="${option}"]`).then((element) => {
        cy.get(element).should("have.value", option);
      });
    });
});

2. “.should(‘not’)”:

We can use `.should(‘not’)` to negate assertions or means to validate negative assertions.

cy.get('button').should('not.be.disabled');//assertion for validating disable button

3. “`.should()` with Chaining Functions”

You can use chaining functions ( when we want to club multiple operations) for more complex assertions and use their methods to specify the expectation.

cy.get('ul')
  .should('have.class', 'active')
  .and('have.attr', 'data-testid', 'my-list')
  .and('contain', 'List Item 1');
 

4. “.expect()”:

The `.expect()` function is used for more complicated assertions, and it is often used with chaining commands. It’s similar to `.should()`, but it allows you to make multiple assertions on the same subject.

cy.get('p').should('have.length', 3).expect($p => {
    // Custom assertions using jQuery methods on the selected elements
    expect($p.eq(0)).to.contain('First paragraph');
  });
expect("expectedText").to.have .text("actualText") ; // asserting Expect to validate text or number
expect("value").to.be.a("string"); //Asserting the data type of the actual value

Real-time example:

When("The button {string} is {string}", (text, status) => {
  cy.get(`button:contains("${text}")`).then(($btn) => {
    if (status === 'enabled') {
      expect($btn).not.to.have.class('Mui-disabled');
      expect($btn).not.to.have.attr('disabled');
    } else {
      expect($btn).to.have.class('Mui-disabled');
      expect($btn).to.have.attr('disabled');
    }
  });
});

Test-Driven (TDD) Assertions in Cypress

TDD (Test Driven Development), in TDD, we follow the approach: first test, then develop. And the coding style which we follow is “Arrange/Act/Assert (AAA)”, Arrange refers to setting up all the preconditions which are required for testing, Act refers to performing the actions which are required for testing, and Assert refers to the verification of outcomes which we are getting. The function that is used for performing assertions is assert()

`.assert()`:

The `.assert()` command is similar to `.should()` and is used for making assertions about elements and properties. When it gets into details, we need .assert() to fetch and validate.

cy.get('input').assert('have.attr', 'type', 'email');  // Checks if the input has the "type" attribute with value "email"
cy.get("#element").then(($el) => {
  assert.isTrue($el.hasClass("some-class"))
}); //asserting the class check for element
cy.get("#element").then(($el) => {
  assert.isTrue($el.is(":visible"))
}); //asserting a check for visibility of element

cy.get("#element").then(($el) => {
  assert.isTrue($el.is(":hidden"))
}); // asserting that an element is hidden
cy.get("#element").then(($el) => {
  assert.equal($el.attr("type"), "text")
}); // asserting element has a specific value

  Real-time example:

const checkStatus = () => {
    if (loopCount >= 10) {
      assert.fail('Exceeded maximum number of attempts to check pipeline status');
    }

Chai-jQuery Assertions Explained

Chai and JQuery assertions are made up of Chai & JQuery, JQuery is used to identify and locate web elements on the page. Chai helps in making assertions about their current state and availability. It validated the properties of the web elements present on the page using.Should().

This assertion is widely used in automation frameworks, first we need to include the Chai-Jquery dependency.

import 'cypress-jquery';

Practical Examples of Chai-jQuery Assertions

// Check if element with a specific class exists or not
cy.get('.element').should('exist');

// Check if element is visible or not
cy.get('.element').should('be.visible');

// Check if element contains specific text or not
cy.get('.element').should('contain', 'Hello, World!');

// Check if an element has a specific CSS class
cy.get('.element').should('have.class', 'active');

// Check if input field has a specific value
cy.get('input[name="password"]').should('have.value', 'john_doe');

// Check if element has a specific attribute
cy.get('a[href="/home"]').should('have.attr', 'target', '_blank');

Real-time example:

When("I click {string} option of side menu", (text) => {
  cy.get('[role="button"]').contains(text).should("have.text", text).click();
});

Sinon-Chai Assertions in Cypress

Sinon-Chai assertion is one of the most widely used assertion libraries in the Cypress UI automation framework. Cypress has multiple key features, but one of them is the most important as it reduces the external dependencies in a controlled environment using simulated behaviour. We use this assertion to manage the stub calling and keep count of it in order to streamline the simulated behaviour. 

Few examples of the assertions that we use in stubbing:

Assert to validate that a stub has been called several times.

const obj = {
  teststub() {
    console.log("hello world welcome")
  },
}
cy.stub(obj, "myMethod")
obj.teststub()
obj.teststub()
obj.teststub()

expect(obj.teststub).to.have.callCount(5)
// assertion to validate a stub has been called for a number of times.

Assert to check that a spy has been called on the test

const spy = cy.spy()
const test= { method: spy }
obj.method()
expect(spy).to.have.been.calledOn(test)
// assert to check a spy has been called on test


Assertion to validate that a stub has not been called

const obj = {
  myTest(arga: string, argb: string) {
    console.log(arga, argb)
  },
}
cy.stub(obj, "myTest")
expect(obj.myTest).to.not.have.been.called
// assertion to validate a stub has not been called

Conclusion

So, after discussing all the assertions in detail for Cypress, the conclusion is that with the help of a rich and resourceful library provided by Cypress, we can validate, check, and identify issues on web applications using automation conveniently and with speed. It can be implemented quickly, and the execution of this automation is fairly simple; any person with limited knowledge can perform the execution and fetch the results using reports. With assertions, we can guarantee the validation of each and every object that is present in the application.

Also, read this detailed guide on Cypress Test Automation