Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use element by css to check if element exists in Protractor

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?

like image 740
Michiel Avatar asked Jan 19 '15 12:01

Michiel


People also ask

Which method is used to find all elements in protractor?

ElementArray (element.ElementArrayFinder is used to get an array/list of elements and perform operations on them. You can call an array of elements and filter them by condition to return a new element. After getting the new element and using then() function to perform operation on new element.


2 Answers

You can test whether the element is present with isPresent. Here are the protractor docs for the isPresent function.

So, your code would be something like:

var myElement = element(by.css('.elementClass')); expect(myElement.isPresent()).toBeFalsy(); 
like image 197
Davin Tryon Avatar answered Sep 20 '22 20:09

Davin Tryon


You need to test if the element is not present:

expect(element(by.css('.elementClass')).isPresent()).toBe(false); 
like image 35
JB Nizet Avatar answered Sep 23 '22 20:09

JB Nizet