Unable to see toast in cypress

Viewed 558

I'm unable to see toast messages on cypress. Tried the test on browser and Command line. Also tried adding wait.

it('Login with invalid password', () => {
    login.enterEmail(testData.username)
    login.enterPassword(testData.invalidPassword)
    login.submit()
    cy.wait(2000)
    login.getToastError().contains(testData.invalidCredentialsError)
})

Any inputs regarding toast messages with cypress will be useful. Thanks in advance.

3 Answers

The problem you face is that the toast appears slowly (compared to test running speed).

TLDR: Use cy.contains('my-selector', 'my-text')


Using cy.get('my-selector').contains('my-text') retries the text my-text, but not the existence of my-selector.

Using the format cy.contains('my-selector', 'my-text') will wait for the element to appear, then check it's text.

So, for a toast that has id="toaster"

it('Login with invalid password', () => {
    login.enterEmail(testData.username)
    login.enterPassword(testData.invalidPassword)
    login.submit()
    cy.contains('#toaster', testData.invalidCredentialsError)  
})

Or pass the error text into login.getToastError

it('Login with invalid password', () => {
    login.enterEmail(testData.username)
    login.enterPassword(testData.invalidPassword)
    login.submit()
    login.getToastError(testData.invalidCredentialsError)  
})
// login - approximate revision

getToastError(errorMessage) {
  if (errorMessage) {
    cy.contains('#toaster', testData.invalidCredentialsError)
  } else {
    return cy.get('#toaster').invoke('text')
  }

Assuming that login.getToastError() translates into something like cy.get('selector') then you can do something like this:

For partial text match:

it('Login with invalid password', () => {
  login.enterEmail(testData.username)
  login.enterPassword(testData.invalidPassword)
  login.submit()
  login
    .getToastError()
    .should('be.visible')
    .and('include.text', testData.invalidCredentialsError)
})

For exact text match:

it('Login with invalid password', () => {
  login.enterEmail(testData.username)
  login.enterPassword(testData.invalidPassword)
  login.submit()
  login
    .getToastError()
    .should('be.visible')
    .and('have.text', testData.invalidCredentialsError)
})

This worked for me when I was needing to verify it was present and had the correct message. I probably didn't need the selector in the .contains() but it works.

cy.get('ion-toast').should('exist').shadow().contains('.toast-message','Invalid username or password.');

The .shadow() method was the magic to see the internals of the toast.

Related