简体   繁体   中英

How do I make Protractor wait for a triggered promise to resolve?

So I have a site where upon clicking a button, it sends off to an angular service, which makes a promise, resolves it, gets some data, and displays that data on the page. I want an angular test that finds the button, clicks it, and verifies that I got data back. However, the test always finishes before the button resolves. I tried browser.sleep(), but that only paused things an the promise was never resolved. Many other promise-related questions here regarding protractor don't help, because the promise was not set up in the test, but by the page itself.

Here is my test:

it('should roll a d2', function () {
    element(by.id('d2Button')).click();

    //whatever has to be here for the waiting to occur

    expect(element(by.binding('rolls.d2')).getText()).not.toEqual('0');
});

Here is the HTML:

<button id="d2Button" type="button" class="btn btn-success" ng-click="rollD2()">Roll</button>
<span><b>{{rolls.d2 | number}}</b></span>

Here is a brief summary of the angular code called on the click:

$scope.rollD2 = function () {
    diceService.getD2Roll($scope.quantities.d2).then(function (data) {
        $scope.rolls.d2 = data.roll;
    });
};

And here is the service call:

function getD2Roll(quantity) {
    var url = "Dice/D2/" + quantity;
    return getPromise(url);
}

function getPromise(url) {
    var deferred = $q.defer();
    $http.get(url).success(deferred.resolve).error(deferred.reject);
    return deferred.promise;
}

How do I make the test wait correctly?

The answer here is to use the built in browser.waitForAngular() functionality after the button click. I made a common method for all tests to use that looks like this:

app.clickButtonAndWaitForResolution = function (button) {
    button.click();
    browser.waitForAngular();
};

Then any test that needs to click a button that fires an AJAX call will call this function and pass in the button element to be clicked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM