How to check if an element is not clickable with Protractor?

19,167

Solution 1

I have found a solution that works for this. As click() returns a promise you can simply .then off of it and throw in the successful click handler and override the catch handler to do nothing which makes the test pass if the element is not clickable.

return this.shouldSeeDisabledFunds()
    .then(function() {
        fundsElem.first().click()
            .then(
                function() {
                    throw "Can click Funds element that should be disabled";
                },
                function() {}
            )
        ;
    })
;

Solution 2

Maybe not applicable in your case, but a better way to check if an element is clickable is checking if it is both visible and enabled: elem.isDisplayed() and elem.isEnabled(). This way you don't accidentally click on buttons when you're not supposed to.

Fyi, there will be a library coming to help with cases like this: https://github.com/angular/protractor/pull/1703

Share:
19,167

Related videos on Youtube

Seer
Author by

Seer

I'm Elliot Wright, a PHP web developer from the UK. I've only been web developing for about 2 and a half years now and have around 8 years of experience with HTML and CSS. I'm a pretty laid back kind of guy. In my spare time I enjoy music, and practice various martial arts.

Updated on June 04, 2022

Comments

  • Seer
    Seer almost 2 years

    It's trivial to test if an element is clickable with Protractor, but I'm stuck scratching my head trying to figure out how to check if an element is not clickable.

    I've attempted to wrap the click function in a try/catch so that when an error is thrown when trying to click it should catch it and let the test pass; however, this does not work.

    Here is my code for the method that does the check:

    return this.shouldSeeDisabledFunds()
        .then(function() {
            var clickable = true;
    
            try {
                fundsElem.first().click();
            } catch (e) {
                clickable = false;
                console.log(clickable);
            } finally {
                console.log(clickable);
            }
    
            console.log(clickable);
    
            // All the way through, clickable is still true, and the console log in the
            // catch is not called. I believe this is because click is asynchronous.
        })
    ;
    
    • Ben Fortune
      Ben Fortune over 9 years
      Does click() not return a promise?
  • I-Lin Kuo
    I-Lin Kuo almost 7 years
    It should be noted that this solution has a side effect of actually clicking the element. It would be nice if there was a solution that could return the information without the side effect.