javascript - Protractor :获取元素的 Id

标签 javascript protractor

一般来说,我在 Protractor 和 javascript 中到处都遇到过这种异步调用。以前需要 2 行代码,现在需要 10 行。这是一个例子:

我正在编写一个 Protractor 实用程序方法来简单地检查一组相关的 div 和输入文本框上的某些 DOM 属性。这是我正在研究的验证框架。这个想法是将 Protractor 元素传递给此方法,然后根据该元素的 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); 
}

应该就是这么简单

关于javascript - Protractor :获取元素的 Id,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36237457/

相关文章:

javascript - 要通过手机移动 3d 图表 Highcharts?

javascript - 如何使用 Protractor conf js测试单独的环境名称?

javascript - 使用Md-select时,如何在 Protractor 中下拉列表?

Javascript:避免在涉及大量循环的代码中使用全局变量

javascript - 添加隐藏列表的平滑效果

javascript - 在 React js 中做一次,然后每 15 秒做一次

javascript - 如何使用存储在 session 存储中的访问 token 通过 HttpClient 进行 Web api 调用?

angular - mat-menu-item 在 Protractor e2e 测试中不可点击

protractor - 在 Bitbucket 管道中运行 Angular 2 Protractor

javascript - Protractor :如何定位给定元素的 sibling ?