Understanding Assertions Cypress

Cypress has a list of common assertions that can be applied to any element on the browser. Assertions are the checkpoints that confirm if a test step of the automated test case passed or failed. Thus it checks the expected state of the application under test.

Cypress bundles the Chai, JQuery and Sinon libraries for assertions. Some of the assertions are associated with the element along with the parent command and cannot be used as a standalone command. For example, should().

However there are some assertions which act upon directly on the elements and not dependent upon other commands. For example, expect(). Though Cypress gives various assertions, there may be situations where Cypress automatically uses the built in assertions without needing to explicitly use them.

These are known as Default Assertions. Some of them are listed below −

  • cy.visit () − awaits the page to display the text or html with 200 status code.

  • cy.request () − awaits the remote server to be present and give a response.

  • cy.contains () − awaits the element with content to be present in the DOM.

  • cy.get () − awaits the element to be present in DOM.

  • .find () − awaits the element to be present in DOM.

  • .type () − awaits the element to be in a type able state.

  • .click () − awaits the element to be in a clickable state.

  • .its () − awaits the element to find a property on the present subject.

Some of the very common assertions are listed below −

  • Length − Verifies the count of the number of elements returned by the previously chained command.

  • Value − Verifies if the element has a particular value.

cy.get('.input-txt').should('have.value', 'Tutorialspoint');
  • Class − Verifies if the element contains or not contains the specified class or not.

cy.get('#tutor').find('a').should('have.class', 'enabled');
  • Text Content − Verifies if the element has a particular text.

cy.get('.input-txt').parent('div').should('contain', 'Tutorialspoint');
  • Visibility − Verifies if the element is visible or not.

  • Existence − Verifies if the element is present in the DOM.

  • CSS − Verifies the css properties of the element.

cy.get('.text-area').should('have.css', 'text-highlight');


Code Implementation with assertion.

// test suite
describe('Tutorialspoint Test', function () {
   // test case
   it('Test Case1', function (){
      // test step to launch a URL
      // enter test in the edit box
      // wait for some time
      // assertion to validate the number of search results
      cy.get('.clsHeadQuestion'). should('have.length',19);

Updated on: 05-Aug-2020


Kickstart Your Career

Get certified by completing the course

Get Started