newcasio
newcasio

Reputation: 253

Test only if element still present

I have a notification message which pops up upon saving a file and wish to close it only if it is still present when I need to press the next button which may be covered by this notification.

So far this is how I have tried to conditionally close the notification

Cypress.Commands.add('notificationClose', () => {
  if (cy.get('.notification').should('be.visible')) {
    console.log('CLOSE ME');
    cy.get('.notification-dismiss').click({mulitple: true});
  }else{
    console.log('ALREADY GONE');
  }
});

I have also tried a jQuery solution I found here too.

Cypress.Commands.add('notificationClose', () => {
  if (Cypress.$('.notifications-wrapper') == true) {
    cy.get('.notification-dismiss').click({mulitple: true});
  }
});

I only use this immediately before needing to click the subsequent button, so the notification may close on its own.

The element in question is only temporarily attached to the DOM after saving the file.

How do I ask if this element is attached to the DOM?

Upvotes: 0

Views: 796

Answers (1)

Mr. J.
Mr. J.

Reputation: 3741

I'm not completely sure that I understand your issue. But this is what I assume you mean:

  1. You have a popup that isn't closed sometimes.
  2. If the popup isn't closed you want to close it.
  3. If the popup is closed you want to continue the test.

If that is correct we only need to fix step 1 and 2 since those are special. Continuing the test is just like you normally do.

To get the behaviour you need to get() the element and assert if it is present. You can do that with this code:

cy.get('body').then($body => {
  if ($body.find('.notification').length === 1) {
    cy.get('.notification-dismiss').click()
  }
})
// continu the test

Upvotes: 1

Related Questions