How to validate a error message in cypress?

6k Views Asked by At

Am new to cypress and been trying to validate an error message that appears on UI after clicking on a button

I've tried the following 3 but neither of them worked

cy.get('pvd-system-message').should('have.text', 'SSN 123456789 not found ')

cy.contains('SSN 123456789 not found').should('be.visible')  

cy.contains('pvd-system-message', 'SSN 123456789 not found ')

Any help would be really appreciated, thank you!

Please check the screenshot here Screenshot of UI and elements

enter image description here

2

There are 2 best solutions below

0
On BEST ANSWER

You have a #shadow-root in the image, take a look at the .shadow() examples.

One of these should work

cy.get('pvd-system-message')
  .shadow()
  .find('p.message__bind')
  .contains('SSN 123456789 not found ');

cy.get('pvd-system-message')
  .shadow()
  .find('p.message__bind')
  .should('have.text', 'SSN 123456789 not found ');

cy.get('pvd-system-message')
  .shadow()
  .contains('p.message__bind', 'SSN 123456789 not found ');
6
On

You can assert the error message in the UI by yielding the element & getting its textContent value like so:

cy.get('.message__bind').then($el => {
   const elText = $el.text(); // gets the text content

   // asserts element contains the right text
   cy.wrap(elText).should('have.text', 'SSN 123456789 not found ');
})

You should read more about it here.