I am using the JavaScript testing framework, Protractor.
I have an external utility class file that I am using to organize common logic within my test specs. See Using Page Objects to Organize Tests.
There seems to be an issue when I take a block of code that resolves a promise, and put in into my Helper utility class file, for the same use.
Example:
In an individual spec file, this code works as expected:
test.spec.js:
it('should display the Protractor workflow text', function() {
// match variable
var match = false;
// get elements by tag
var scanElements = element.all(by.css('div')).each(function(el) {
el.getText().then(function(text) {
var sp = text.split(' '); // split by <space>
for (var i = 0; i < sp.length; i++) {
if (sp[i] == 'Protractor') {
match = true;
}
}
});
});
// on complete
scanElements.then(function() {
console.log(match); // returns true
});
});
However, if I separate this logic into my Helper utility class, the return value is undefined
.
Helper.js
/** containsText [process]
* searchs for text in tag elements (i.e. 'string' in <a>, 'string' in <div>)
* @param string - tag name to limit
* @param string - string value to search against
*
* @return boolean - if string is found
*/
this.containsText = function (tagName, stringValue) {
// match variable
var match = false;
// get elements by tag
var scanElements = element.all(by.css(tagName)).each(function(el) {
el.getText().then(function(text) {
var sp = text.split(' '); // split by <space>
for (var i = 0; i < sp.length; i++) {
if (sp[i] == stringValue) {
match = true;
}
}
});
});
// on complete
scanElements.then(function() {
return match;
});
}
test.spec.js
it('should display the Protractor workflow text', function() {
console.log(helper.containsText('div', 'Protractor')); // does not wait to resolve, returns undefined
});
Edit: All of the links to similar questions on Stack Overflow have to deal with asynchronous calls via Ajax requests. I'm looking for a solution for the Protractor / Webdriver framework. I have read documentation on creating promises with Protractor, and have tried the following as well:
Helper.js
this.containsText = function (tagName, stringValue) {
// get elements by tag
var scanElements = element.all(by.css(tagName)).each(function(el) {
el.getText().then(function(text) {
var sp = text.split(' '); // split by <space>
for (var i = 0; i < sp.length; i++) {
if (sp[i] == stringValue) {
return true; // fufill outer promise and break execution
}
}
});
});
return scanElements;
}
test.spec.js
helper.containsText('div', 'Protractor').then(function(f) {
console.log(f);
});
Still looking for some assistance.