Search code examples
javascriptseleniumprotractorexpected-condition

How to manually use a protractor ExpectedCondition?


I'm new to protractor and I want to create an expect like this:

expect(elementIsVisible).toBe(true);

I saw that protractor has EC (expected conditions), namely EC.visibilityOf which seems to be what I'm looking for. However, I'm not entirely sure what visibilityOf returns.

I find the docs very obscure:

RETURNS
+-----------+-------------------------------------------------------------------------------------------+
|   Type    |                                        Description                                        |
+-----------+-------------------------------------------------------------------------------------------+
| !function | An expected condition that returns a promise representing whether the element is visible. |
+-----------+-------------------------------------------------------------------------------------------+

What it returns? A Promise or an expected condition?

Well, considering that chaining a .then triggers then is not a function, it seems it returns an expected condition. But what's that?

In all Protractor documentation examples, this return value is used in browser.wait functions.

I don't want to use it like that, I want to have a true/false value in my expect condition.

If I try to find more information from Selenium's examples, Protractor (a javascript implementation) redirects to Java documentation...


Solution

  • visibilityOf and all other ExpectedConditions return functions. You can call this function, and you will get Promise<boolean> . Basically all ExpectedConditions are predicates - functions, that when called return promise resolved to boolean (should be no exceptions thrown). So basically you can try to use something like this:

    let shouldBeVisible = protractor.ExpectedConditions.visibilityOf
    expect(
        shouldBeVisible($('div.button'))() // Notice () - this where we are manually calling predicate function to get boolean result
    ).toBeTruthy('Element div.button should be visible');
    

    But lucky you - if you are using JasmineJS - you can try my lib to assert visibility of elements: https://github.com/Xotabu4/jasmine-protractor-matchers

    So you will get not just checking element visibility, but matcher will automatically wait for a while to element to become visible. Check this:

    expect($('div.button')).toAppear()

    More examples in README.MD