Cypress and Command

Profile picture for user arilio666

The And Command in Cypress is often used as a chaining assertion which means it is coupled with an assertion that has the yielded selector to pass onto the and command to follow it.

  • If you are familiar with the should assertion, this and assertion is always coupled up with the should assertion which is the correct usage of this assertion.
  • should is followed by and as the should yield the selector it absorbed and passes it to the and command.
  • and is an alias of .should()

Syntax

.and(chainers)
.and(chainers, value)
.and(chainers, method, value)
.and(callbackFn)
  • chainers: any valid chainer that comes from chai, chai-jquery or sinon-chai. 
  • value: value to assert against chainer
  • method: a method to be called on chainer
  • callbackFn: Pass a function that can have any number of explicit assertions within it.

Usage Of And The Right Way

cy.get('#id').should('be.visible').and('contain','example text')

Usage Of And The Wrong Way

cy.and('eq','10')

Example: Cypress Chaining Assertions

For example purpose, we will be using the https://www.programsbuzz.com/user/login site to add in the chain assertion.

it('and demo ',()=>{
    cy.visit('/')
    cy.get('#edit-name')..type('Man Mala Man')
    cy.get('#edit-pass').type('mamamamama')
    cy.get('#edit-submit').click()
        
    cy.get('.messages--error').should('be.visible').and('contain','Unrecognized username or password. Forgot your password?')
    })
})

Here's the code that will check the login functionality of the site but we want just the chained assertion and command alone.

cy.get('.messages--error').should('be.visible').and('contain','Unrecognized username or password. Forgot your password?')
  • So here in the last test step, we can see the assertion of and.
  • Here we have got the error message out of the incorrect login detail in getting.
  • From get the yielded result passes to should and we are asserting it should be visible there.
  • From the yielded result of should the and command get the yielded subject and checks whether it contains the error message.
  • From this, we can conclude that both should, and are chained assertion passed on to assert something of the yielded subject and both must be asserted true that is the true purpose of and.

Cypress Chaining Assertions

Here we can see the assertions getting passed as the error messages are both visible and contain the error text that they should contain.