d.rodriguez d.rodriguez - 3 months ago 10
Javascript Question

Return value and/or breaking out of a promise in javascript

I know this similar question is out there, but I haven't really been able to take much from the answers found from them. I'm not trying to be lazy here and not do my research first, because I have!

I'm using Protractor/Jasmine in JavaScript.

I have a method stored in a page object file:

this.verifyUserExists = function (username){
driver.findElements(by.css('.ui-datatable-data > tr > td:nth-of-type(1)')).then(function (elements) {
for (i = 0; i < elements.length; i++) {
(function (index) {
elements[index].getText().then(function (users) {
if (users.trim().toLowerCase() == username.trim().toLowerCase()) {
console.log('Username: ' + users.trim() + ' found in the list.');
expect(true).toBeTruthy();
}
}).catch(function (err) { });
})(i);
}
}).catch(function (err) { });
}


And in my main test I would do
obj.VerifyUserExists('anon123');


As seen, the method accepts a string username and searches for it via a list of usernames in a table. The code works, if the user exists, and the test passes. However, if the user DOES NOT exist and is not the last item in the list, it falsely fails.

For example:

if (users.trim().toLowerCase() == username.trim().toLowerCase()) {
console.log('Username: ' + users.trim() + ' found in the list.');
expect(true).toBeTruthy();
}
else {
//expect to fail
}


With the above - if we have 5 usernames, 4 of them will falsely fail.

I tried adding a boolean flag, but it comes back undefined everywhere. So my question is how would I do something like the following:

if(user == username){
//true
//exit
}
else if (end of list && name not found)
{
//false
//exit
}

Answer

Instead of looping through all the elements you can directly get the text of all elements and use expect().toContain() matcher to check if the required value exists in the locator. Look at below example.

var displayedUserNames = element.all(by.css('.ui-datatable-data > tr > td:nth-of-type(1)')).getText(); 
//above line will get you all available username as Array.
expect(displayedUserNames).toContain(actualUserNametobeDisplayed)
Comments