top of page

Cypress Tutorial

Assertions In Cypress

What Are Cypress Assertions ?

Cypress has multiple assertions obtained from various assertion libraries, like : mocha, chai, jquery and so on. Cypress assertions are broadly classified in two segments as :
  • Implicit Assertions

  • Explicit Assertions

What are Implicit Assertions in Cypress ?
Assertion that applies to the object obtained from the parent chained command is an implicit assertion. This class of assertions include command such as : .should(), .and() .
These commands cannot be used as standalone and depend on previously chained command. Generally, they are used to verify multiple checks on a particular object.
Consider the following example :


Here .should() is used to apply assertion on the chained command and .and() is used to assert multiple things against the same element.
Some common Cypress commands are :
  • length - To check the number of elements returned by the chained command.

cy.get('li[class="itemDepth02233374943__itemWrapper"]').should('have.length',7)

  • value - To check whether the element contains a certain value.

cy.get('#input_search-box-input-comp-l3sv00z9').type("Cypress")

.should('have.value','Cypress')

  • class - To check whether the element does have or doesn't have the mentioned class.

cy.get('#input_comp-l3mqh23b2').should('have.class','_1SOvY has-custom-focus')

  • contain - To check whether the web element contains a certain text/subtext.

cy.get('div[id="comp-l3ocgd8b"]')

.find('span[style="letter-spacing:normal;"]').should('contain','Simple')

  • visible - To check visibility of a web element.

cy.get('#comp-l4ccuev8 > a').should('be.visible')

  • exist - To check existense of a web element.

cy.get('#input').should('not.exist')

  • state - Validate state for radio or checkboxes.

cy.get(':selector').should('be.checked')

  • css - To check css property of the webelement.

cy.get('div[id="comp-l3ocgd8b"]>h5').should('have.css','font-size','22px')

Below is an example code to demonstrate these commands :



The output would be as :

​​


What are Explicit Assertions in Cypress ?
Assertion applicable directly to an object, is known as Explicit assertion. There's no need of any chained command for this type of assertions.The common explicit assertions are expect() and assert().
Generally, expect() is used for comparing two or more things whereas assert() verifies a specific condition like : type, length, boolean, equality and so on.
Consider the following example :



The output will be :


Refer next page Cypress Hooks
bottom of page