Aneesh
Aneesh

Reputation: 599

Protractor - getText as input to sendKeys and other actions

I am writing a protractor test, where I need to read a span/div with id='mylabel' using getText(). I then need to pass the value to an input (id='myinput') using sendKeys().

So, I do this:

var value;
element(by.id('mylabel')).getText().then(function(txt){
    value = txt;
    element(by.id('myinput')).sendKeys(value);
    // do "other protractor tasks" with 'value'.
})

But, is there a way I can avoid the nesting, by asking protractor to perform sendKeys and subsequent actions only after the value variable is set?

The above is a simple case, but I soon find code getting into multiple nesting because of the waiting for promises to be resolved. Also, I observed that protractor does not provide a stacktrace if "other protractor tasks" throws an error due to an error somewhere down the line (it just hangs and times out).

I am using Protractor 2.1.0 and I am working with Angular JS pages.

I am specifically interested to know if it is a known issue to have silent errors in nested tasks with Protractor and is there anyway to solve it?

Upvotes: 3

Views: 676

Answers (2)

Zakir Sayed
Zakir Sayed

Reputation: 200

Protractor handle at least one level of promises without the need of then function. That way you can expect synchronous flow.

If you are looking for event based action like watching a value to update then you can setup something like this:

function waitForTextToUpdate(elm, defaultText, timeout) {
    if (typeof(timeout) === 'undefined') {
        timeout = 10000;
    }
    return browser.driver.wait(function() {
        return elm.getText().then(function(value) {
            return !(value.indexOf(defaultText) > -1);
        });
    }, timeout, "Expectation error (waitForTextToUpdate): Timed out waiting for element state to change.");
}

Upvotes: 2

giri-sh
giri-sh

Reputation: 6962

Promises are inevitable in protractor. There is no way to avoid handling promises, but if you want to avoid nesting it can be done easily using .then() chaining functionality. Here's an example -

var value = '';
element(by.id('mylabel')).getText()
.then(function(txt){
    value = txt;
})
.then(function(){
    element(by.id('myinput')).sendKeys(value);
    // do "other protractor tasks" with 'value'.
});

There's also an npm package available for this feature. Q npm package. It works similar to the above example but is more extended. Hope this helps.

Upvotes: 1

Related Questions