user812142
user812142

Reputation: 173

Protractor - Jasmine . Perform some action only when a specific element is present.

I have a window-box with two buttons 'add' and 'close'. I need to test below scenario: When clicked on 'add' button it throws error and the window remains open. I need to click on 'close' button to proceed.

I used below code:

if(element(by.xpath("xpath_of_error_box")).isEnabled()) 
    {   
        element(by.xpath("xpath_of_close_button")).click();
    }

But it throws below error:

No element found using locator: By(xpath, xpath_of_error_box)

Is there any way to handle this?

Upvotes: 1

Views: 332

Answers (3)

factor5
factor5

Reputation: 330

According to the error, it seems that your xpath locator didn't match any element. And according to the additional clarification in the question you could try:

element(by.xpath("xpath_of_error_box")).isDisplayed().then(isDisplayed => {
    if (isDisplayed) {
    // do what you need when it is visible
    } else {
    // if not then proceed
    }
});

As it was pointed out, isEnabled might not be the proper method you should use in this case. If it seems that the element you try to find is always present in the dom, you might better try to check for its visibility using isDisplay instead. An advice. It's not a good idea to use xpath locators in your tests, because this ties them to the html DOM structire of the web page you are observing. As we know, the UI happens to change often, which would make your tests to brake often as well. Although this is of cource a personal preference, it is such until you end up with tons of brocken tests after a single small change in the html.

Upvotes: 1

technodeath
technodeath

Reputation: 123

  1. isEnabled() and isPresent() returns promise (not boolean) and have to be resolved.
  2. isEnabled() could be only used for <button>.
  3. You can use XPath all the time, don't listen to anyone.

PS. Of course it would be glad to see your HTML to check the correctness of your XPath.

Upvotes: 0

JakyStars
JakyStars

Reputation: 3

If you need to check if an element is present you can use the following code:

if (element(by.xpath("yourXpath")).isPresent())

But your problem is not on your if code, your problem is that the xpath your are searching doesn't exist.

Upvotes: 0

Related Questions