Cypress should command

Profile picture for user arilio666

In cypress, there is a cool assertion feature called 'should' which is used to assert if something is visible or empty or equals to. Assertions are a way of validating whether the thing which is needed is present or you can say Assertions state confidently that application behavior is working as expected..

Syntax:

.should(chainers)
.should(chainer, value)
.should(chainer, method, value)
.should(callbackFn)

Here,

  • chainers (String): Any valid chainer like have.class, have.css, have.attr etc that comes from Chai, Chai-jQuery or Sinon-Chai.
  • value (String): Value to assert against chainer. For example: have.attr can have a value href and have.id can have value header.
  • method (String): A method to be called on the chainer.
  • callbackFn (Function): Pass a function that can have any number of explicit assertions within it. Whatever was passed to the function is what is yielded.

Example:

Demo Website: http://www.autopract.com

it.only('should demo', () =>{
    cy.visit("/");
    cy.get("button.close").click();
    
    // verify url contains value
    cy.url().should('include','/#/home/fashion')
    
    // verify element text - cart contain 0 element
    cy.get("span.cart_qty_cls").should('have.text','0')

    // verify logo image class
    cy.get("a#headerlogo img").should('have.class','img-fluid')

    // Attribute contains value using should
    cy.get("a#headerlogo").should('have.attr','href','#/home/fashion')
  })

Note: Always use should with a chain of validation.

cy.should('have.attr','href','#/home/fashion')

In above statement we have not used should along with any get statement, this is fine if you are using this just after desired command but in other case it will give you error. For example, if you will use it after a#headerlogo it will not return any error but in case you will use same statement after a#headerlogo img it will fail the assertion since above should is associated with a#headerlogo , using it after a#headerlogo img will make it part of that command and hence fail.

We have discussed basic usage of should but it is applicable to many elements with different chainers. We can also use methods and callback function with should which we will discuss later.