chrisl08
chrisl08

Reputation: 1658

Protractor: get Element's Id

I have had it with this asynchronous calls all over the place in protractor and javascript in general. What used to take 2 lines of code now takes 10. here's an example:

I am writing a protractor utility method to simply check for certain DOM properties on a group of related divs and input text boxes. This is for a validation framework I am working on. The idea is to pass a protractor element to this method and then based on that element's id check for certain DOM properties on related divs and input text boxes. This is how I got it to work:

/**
 * Checks for error in a NUAF field 
 * @param {String or Element} field . 
 * @param {string} errorText expected validation error text to appear in tooltip
 */
exports.checkForError = function (field, errorText) {

    var innerCheck = function(fieldId) {
        expect(fieldId).not.toBe(undefined);
        var elmntd = element(by.id('divInput.'+fieldId));
        expect(elmntd).not.toBe(null);
        expect(elmntd.getAttribute('tooltip')).toContain(errorText);
        expect(exports.hasClass(element(by.id('prnt.'+fieldId)), 'has-error')).toBe(true);
    };

    // this unbelievably complex block of code gets the id of the 
    // field argument.  If string was passed, the fieldid is just that .
    if (typeof field === 'string') {
        innerCheck(field);
    } else {
        //what used to be field.id now needs 6 lines of code?
        field.getAttribute('id').then(
            function(idAttribute) { 
                console.log( "*********: "+idAttribute );
                innerCheck(idAttribute);
            }
        ); 
    }
};

Question is: Is there a better, less verbose way to write the field.getAttribute('id').then block of code. It's just a shame to write all this just to get the Id of the element.

Upvotes: 4

Views: 2528

Answers (1)

smnbbrv
smnbbrv

Reputation: 24541

This is not that verbose for an asynchronous code... Especially if you take into account that you can directly pass the function innerCheck to a promise:

// this unbelievably complex block of code gets the id of the 
// field argument.  If string was passed, the fieldid is just that .
if (typeof field === 'string') {
    innerCheck(field);
} else {
    field.getAttribute('id').then(innerCheck); 
}

Should be just that easy

Upvotes: 4

Related Questions