How to conditionally click an element in Protractor?

Viewed 72

In a protractor test, I need to close a pop-up if it appears (it doesn't always) and proceed with the test as normal. Here's the code I've got to do so-

let checkForPopUp = async function() {
  element(by.css('button[id="gdprStopEmails"]')).isPresent().then(function (isVisible) {
    return isVisible;
  });
}

it('description', async function() {
      let hasPopUp = await checkForPopUp();
      if(hasPopUp) {
        await element(by.id("gdprStopEmails")).click();
      }
      await connectedAccounts.revokePermission(partnerInfo.revokeId, partnerInfo.confirmRevokeId);
    });

I ran this test a few times without checking if the element was there, and it closed the popup every time it was there (and failed the test when it wasn't). It hasn't closed the popup a single time since I introduced the condition check, and despite my best efforts I can't figure out what's up. Does anything jump out to you guys? Thanks in advance!

1 Answers

you're missing return. Your function returns nothing explicitly and thus implicitly returns undefined which is always falsy, and your if block doesn't get executed

This should work

let checkForPopUp = async function() {
  return element(by.css('button[id="gdprStopEmails"]')).isPresent().then(function (isVisible) {
    return isVisible;
  });
}

it('description', async function() {
      let hasPopUp = await checkForPopUp();
      if(hasPopUp) {
        await element(by.id("gdprStopEmails")).click();
      }
      await connectedAccounts.revokePermission(partnerInfo.revokeId, partnerInfo.confirmRevokeId);
    });

but since you're using async/await don't mix syntaxes. I'd do it this way

let checkForPopUp = async function() {
  return element(by.css('button[id="gdprStopEmails"]')).isPresent()
}

it('description', async function() {
      let hasPopUp = await checkForPopUp();
      if(hasPopUp) {
        await element(by.id("gdprStopEmails")).click();
      }
      await connectedAccounts.revokePermission(partnerInfo.revokeId, partnerInfo.confirmRevokeId);
    });

and keep in mind isPresent doesn't guarantee the visibility

Related