Jackie
Jackie

Reputation: 23607

How do can I create a isVisible function in JS using Protractor?

I would like to do something like this but it doesn't work because isPresent returns a promise and not a boolean...

this.isVisible = function(){
  return browser.isElementPresent(_this.username) &&
         browser.isElementPresent(_this.password) &&
         browser.isElementPresent(_this.submit)
}

I also tried

this.isVisible = function(){
  return _this.username.isPresent() &&
         _this.password.isPresent() &&
         _this.submit.isPresent()
}

Is there a way to handle this? Perhaps use all and then combine it with a single boolean promise or something?

Upvotes: 1

Views: 22

Answers (1)

alecxe
alecxe

Reputation: 474161

You can use the protractor.promise.all():

this.isVisible = function() {
    return protractor.promise.all([
        browser.isElementPresent(_this.username),
        browser.isElementPresent(_this.password),
        browser.isElementPresent(_this.submit)
    ]).then(function (isPresent) {
        return isPresent[0] && isPresent[1] && isPresent[2];
    });
}

And, if you would add a helper spread() function:

function spread (callback) {
    // and returns a new function which will be used by `then()`
    return function (array) {
        // with a result of calling callback via apply to spread array values
        return callback.apply(null, array);
    };
};

This would make things a little bit more explicit:

this.isVisible = function() {
    return protractor.promise.all([
        browser.isElementPresent(_this.username),
        browser.isElementPresent(_this.password),
        browser.isElementPresent(_this.submit)
    ]).then(spread(function (isUsernamePresent, isPasswordPresent, isSubmitPresent) {
        return isUsernamePresent && isPasswordPresent && isSubmitPresent;
    }));
}

Upvotes: 1

Related Questions