量角器:获取元素's同上

Protractor: get Element's Id

本文关键字:同上 获取 元素 量角器      更新时间:2023-09-26

我在量角器和javascript中的所有地方都有这种异步调用。过去需要2行代码,现在需要10行代码。这里有一个例子:

我正在编写一个量角器实用程序方法,只需检查一组相关div和输入文本框上的某些DOM属性。这是我正在开发的一个验证框架。其想法是将一个量角器元素传递给这个方法,然后根据该元素的id检查相关div和输入文本框上的某些DOM属性。这就是我让它工作的方式:

/**
 * 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);
            }
        ); 
    }
};

问题是:有没有一种更好、不那么冗长的方法来编写field.getAttribute('id').then代码块。写这些只是为了得到元素的Id,真是太可惜了。

这对于异步代码来说并不那么冗长。。。特别是如果考虑到可以直接将函数innerCheck传递给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); 
}

应该只是简单的