Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Protractor - getText as input to sendKeys and other actions

Tags:

protractor

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?

like image 961
Aneesh Avatar asked Dec 06 '25 06:12

Aneesh


2 Answers

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.");
}
like image 142
Zakir Sayed Avatar answered Dec 09 '25 15:12

Zakir Sayed


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.

like image 30
giri-sh Avatar answered Dec 09 '25 15:12

giri-sh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!