DEV Community

Cover image for The Ultimate Guide to Cypress Assertions
rohits613
rohits613

Posted on • Originally published at testgrid.io

The Ultimate Guide to Cypress Assertions

First we will try to understand what exactly is Cypress? and why is it used?

So, Cypress is a new age Test Automation tool used for Web application automation, 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 details , whereas with Cypress we get all the testcases 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 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 as well as negative.

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 getting open with options of 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 be having 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 be keeping 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 getting called out in step definitions. For reporting we can use allure report or HTML report.

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

What are Assertions?

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 getting passed or failed or sometimes we define other flows based on the outputs which 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 which should be there on application. If we are expecting a button to be there on the UI and it should be enabled for that we will be needing 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

BDD Assertions in Cypress

BDD (Behavioral driven development) are 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 function 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
Enter fullscreen mode Exit fullscreen mode

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);
      });
    });
});
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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');
Enter fullscreen mode Exit fullscreen mode
  1. “.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
Enter fullscreen mode Exit fullscreen mode

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');
    }
  });
});
Enter fullscreen mode Exit fullscreen mode

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 perform the actions which are required for testing and Assert refers to the verification of outcomes which we are getting , the function which is used for performing assertion is assert()

1. .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
Enter fullscreen mode Exit fullscreen mode

Real time example:

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

Chai-jQuery Assertions in Cypress
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 property 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';

Enter fullscreen mode Exit fullscreen mode

FEW 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');
Enter fullscreen mode Exit fullscreen mode

Real time example:

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

Sinon-Chai Assertions in Cypress

Sinon-Chai assertion is one of the most widely used assertion libraries in 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 keeping count of it in order to streamline the simulated behaviour.

Few examples of the assertions which we use in stubbing:

Assert to validate a stub has been called for a number of 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.
Enter fullscreen mode Exit fullscreen mode

Assert to check a spy has been called on 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
Enter fullscreen mode Exit fullscreen mode

Assertion to validate 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
Enter fullscreen mode Exit fullscreen mode

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 execution of this automation is fairly simple, any person with limited knowledge can perform execution and fetch the results using reports. With Assertions we can guarantee the validation of each and every object which is present on the application.

Top comments (0)