无法在量角器中使用 getText() 和 getAttribute() 验证文本值

Not able to verify the text value using getText() and getAttribute() in protractor

当我使用下面的代码时,它应该从网页获取数值,但是我得到的值是 [object][object]

下面是我正在使用的代码。

var resultText = element(by.id('output')).getAttribute();
console.log("Result text:  " + resultText);

我也试过下面的方法,但是我无法从网页上得到正确的值。

element(by.id('output')).each(function (element) {              
    var resultText = element.getAttribute('value').then(function(attr){
        expect(typeof attr).toBe("string");
    });
});

你能帮我获取元素的值吗?感谢您对此的帮助。

getAttribute()getText() 总是 returns 一个承诺。因此,您应该使用它 returns 的承诺来获取元素的值,然后控制台记录它或在您的期望语句中使用它。方法如下 -

element(by.id('output')).getAttribute('value').then(function(resultText){
    console.log(resultText);
    expect(typeof resultText).toBe("string");
});

如果 ID 为 output 的元素更多,则使用 .each() 方法检索每个元素的值。

element.all(by.id('output')).each(function (ele) {
    ele.getAttribute('value').then(function(attr){
        expect(typeof attr).toBe("string");
        console.log(attr); //print the value of returned by getAttribute
    });
});

getText() 也以类似的方式工作。这是一个例子 -

element(by.id('output')).getText().then(function(text){
    console.log(text); //print the text that output element holds
});

有关 getAttribute() and getText() 的更多信息。希望这会有所帮助。

你不应该明确地等待 promises 解决(为了可读性),除非你真的必须这样做。以下是有效的期望:

expect(element(by.id('output')).getAttribute('id')).toBe('output'); // true

或事件更短:

expect($('output').getAttribute('id')).toBe('output'); // true