Home > front end >  Cypress negative assertion jumps to next it()
Cypress negative assertion jumps to next it()

Time:06-11

I have three it() blocks within a describe test suite. In the first one I select from a dropdown a given value, then in the next two it() blocks I want to assess that some fields are correctly pre-populated based on the value I selected.

Besides correct assertion I want to also have some negative ones (fields that don't have to be empty). However, when Cypress detects a negative test (line 69) it jump to the next it() block instead of reading remaining assertions from that it() (see line 72).

So after a negative assertion from line 69, line 72 is never reached, but rather the next it() block is executed.

I want to make it so that it would also reach the code from line 72.

enter image description here

CodePudding user response:

That's standard behaviour for Cypress tests, as soon as an assertion fails the current test (i.e the current it() block) terminates.

You could split the next part into another test, or use soft-assertions (but these are not built-in to Cypress).

Another approach is to not use expect(val).to.not.be.empty inline but save all assertion for the end of the test (i.e Arrange/Act/Assert pattern).

Maybe

cy.wrap(frame).find("#email").invoke('val').as('email')
cy.wrap(frame).find("#phoneNumber").invoke('val').as('phoneNumber')
...
cy.get('@email').then(email => {
 cy.get('@phoneNumber').then(phoneNumber => {
   const emailNotEmpty = email !== ''
   const phoneNumberNotEmpty = phoneNumber !== ''
   expect(emailNotEmpty && phoneNumberNotEmpty).to.eq(true)
 })
})

Also .invoke('attr', 'value') may not give you the current value of the input, just the value set on page load.

For current value you want to invoke the val() method.

CodePudding user response:

Be careful when using a negative assertion. You are only checking one incorrect possibility out of many. Here is an example of better assertions for elements with empty string.

It seems the value of the email is empty already. Maybe you grabbing the text would be better and asserting the length is greater than 0 or use a regex matching since the expected text will be in email format.

// assert text length
.invoke('text')
.then((text) => expect(text.length).to.be.gt(0))

// regex matching can be as simple as
.invoke('text')
.should('match', /(\w )@(\w ).(\w )/)
  • Related