简体   繁体   中英

Protractor - looping through different locators to populate array

I'm using protractor and I want to loop through a series of locators(all with different names) to get the text being displayed and then compare that to an array of expected values.

I've come accross examples like below:

var expected = ['expect1', 'expect2', 'expect3'];
var els = element.all(by.css('selector'));
for (var i = 0; i < expected.length; ++i) {
    expect(els.get(i).getText()).toEqual(expected[i]);
}

where you can do a comparison against a locators children, but not from different locators.

How would you adapt something like the one above to loop through a list of locators(like below) and then compare that to a series of values in another array.

const locators = {
    emp: by.id('employmentError'),
    occ: by.id('occupationError'),
    stat: by.id('statError'),
    show: by.id('showError')
}; 

The comparison part seems easier, it is populating the initial array full of text from various locators I can't get my head around.

It looks like you are trying to collect elements that correspond to different types of errors. What if you would get all of them with a unified locator , like:

var errors = $$("[id$=Error]");
expect(errors.getText()).toEqual([
    "Employment Error happened",
    "Some other error" 
]);

Here errors would locate the elements with id attributes ending with "Error".

Protractor methods return promises. So it's safer to use promises every time because they are asyn operations. Try the following code:

const locators = {
    emp: element(by.id('employmentError')),
    occ: element(by.id('occupationError')),
    stat: element(by.id('statError')),
    show: element(by.id('showError'))
}; 
var promises = [], texts = [];
var els = element.all(by.css('selector'));
els.forEach(els, function(el) {
  els.getText().then(function(text) {
    texts.push(text);
  });
});
for (var i in locators) {
  promises.push(locators[i].getText());
}
expect(protractor.promise.all(promises)).to.become(texts);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM