I am asserting on the contents of a particular row from an html table using webdriver via protractor. I have the following code which works correctly, but looks horrible. I want advice on how to better organise this code idiomatically with promises; in particular, I'd like to make it more obvious that there are 3 parts to this code:
- Find the rows with a td containing the specified
matchText
on the page - Check that only one row matched, and handle the error cases with useful debug info
- Check that the text content of the tds in this matched row is as expected
Is there a way I can organise this better to make this more readable, perhaps by chaining the promises or something?
browser.findElements(by.xpath("//td[text() = '" + matchText + "']/..")).then(function(trs) {
if (trs.length == 0) {
throw 'Unable to find td element equal to ' + matchText
} else if (trs.size > 1) {
protractor.promise.all(trs.map(function(tr){return tr.getInnerHtml()})).then(function(trsInnerHtml) {
throw 'Matched multiple td elements for ' + matchText + ':' + trsInnerHtml;
})
} else {
trs[0].findElements(by.tagName('td')).then(function(tds) {
protractor.promise.all(tds.map(function(td) {return td.getText()})).then(function(tdContent){
expect(tdContent).toEqual(expectedContent);
})
});
}
});