Ken Palmer
Ken Palmer

Reputation: 2445

With Protractor, how can I return a boolean from a function

I have a test which calls 2 functions from a page object. When an expectation in the first function succeeds, I want the second function to execute normally. Otherwise, I want execution of that second function to be aborted.

Here is my test with the 2 functions.

it('Should do something.', function () {
    page.expectModalBoldTextOf(('Expected Text'));
    page.clickButton('Yes');
});

And here is the function where I'd like to return a Boolean.

public expectModalBoldTextOf(boldedText: string) : boolean {
    element.all(by.className('modal-body')).filter(function (elm) {
        return elm.isDisplayed().then(function (displayed) {
            return displayed;
        });
    }).then(function (modalBodyArray) {
        if (modalBodyArray.length === 0) { // force a descriptive failure.
            expect('Modal dialog').toBe('displayed on the page');
            return false;
        }
        else {
            modalBodyArray[0].element(by.tagName('strong')).getText().then(function (strongText) {
                expect(strongText.toUpperCase()).toBe(boldedText.toUpperCase());
                return true;
            });
        }
    });
}

Now, the above renders the following Protractor error.

A function whose declared type is neither 'void' nor 'any' must return a value or consist of a single 'throw' statement.

If I change the return type from "boolean" to "any" this function works as desired (when I remove the return statements), but it does not return any indicator to signal that it succeeded or failed so that I can prevent the clickButton function from executing.

I understand that I could call the clickButton() function within the expectModalBoldTextOf() function only when it succeeds. But I'd rather return a boolean to signal success or failure, as that would make this more generically useful in our application.

Upvotes: 1

Views: 2057

Answers (1)

alecxe
alecxe

Reputation: 474161

expectModalBoldTextOf() returns a promise that would be resolved to a boolean by the Control Flow. Put the any return type and explicitly resolve the function result in your test:

page.expectModalBoldTextOf('Expected Text').then(function (succeed) {
    if (succeed) {
        page.clickButton('Yes');
    }
});

Upvotes: 2

Related Questions