49

In a protractor end to end test, I want to check if an element exist using element(by.css(...)), my code:

var myElement = element(by.css('.elementClass'));
expect(myElement).toBeUndefined;

This test fails, it says:

    Expected { locator_ : { using : 'css selector', value : 'div[ng-switch-
    when="resultNav"]' }, parentElementFinder_ : null, opt_actionResult_ :
    undefined, opt_index_ : undefined, click : Function, sendKeys : Function, 
getTagName : Function, getCssValue : Function, getAttribute : Function, getText
 : Function, getSize : Function, getLocation : Function, isEnabled : Function, 
isSelected : Function, submit : Function, clear : Function, isDisplayed : 
Function, getOuterHtml : Function, getInnerHtml : Function, toWireValue : 
Function } to be undefined.

After that I tried to use a promise:

element(by.css('.elementClass')).then( functtion(data) {
    expect(data.getText()).toBeUndefined();
});

This results in an error:

Error: No element found using locator By.CssSelector(...)

Yes, I know that no element will be found, but how can I create a working test using element(by.css(...))?

Does anyone know how to achieve this? or is element(by.css()) not the method to use here?

4

4 回答 4

102

您可以测试 是否element存在isPresent。 这是该功能的量角器文档isPresent

因此,您的代码将类似于:

var myElement = element(by.css('.elementClass'));
expect(myElement.isPresent()).toBeFalsy();
于 2015-01-19T12:15:09.277 回答
28

您需要测试该元素是否不存在:

expect(element(by.css('.elementClass')).isPresent()).toBe(false);
于 2015-01-19T12:15:15.703 回答
1

相同的东西,但语法不同

let elem = $('.elementClass');
let elemIsPresent = await elem.isPresent();
expect(elemIsPresent).toBe(false);
于 2021-02-09T01:41:50.870 回答
1

Truthy 和 falsie 指的是在被强制为布尔值后被评估为 true 和 false 的值,除非您希望函数返回不同类型的值。

var myElement = element(by.css('.elementClass'));
myElement.isPresent().then(function (elm)
{
    if (elm)
    {
        console.log("... Element was found")
        expect(myElement.getText()).toBeUndefined();
    } else {
        console.log("... Element was not found")
    }
});
于 2020-10-15T14:06:08.077 回答