I am having an issue with my website where clicking a button triggers an angular service that returns some data to be displayed on the page. I need to write an angular test that clicks the button, waits for the promise to resolve, and verifies that the data is displayed. However, the test always completes before the promise is resolved. I tried using browser.sleep(), but it didn't work because the promise was never resolved. Most of the suggestions related to promises in protractor tests don't apply here since the promise is set up by the page itself, not within the test.
Below is the test code:
it('should roll a d2', function () {
element(by.id('d2Button')).click();
// Code to wait for promise resolution
expect(element(by.binding('rolls.d2')).getText()).not.toEqual('0');
});
Here is the HTML snippet:
<button id="d2Button" type="button" class="btn btn-success" ng-click="rollD2()">Roll</button>
<span><b>{{rolls.d2 | number}}</b></span>
Summary of the angular code triggered by the click event:
$scope.rollD2 = function () {
diceService.getD2Roll($scope.quantities.d2).then(function (data) {
$scope.rolls.d2 = data.roll;
});
};
And here is the relevant 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;
}
Can someone help me figure out how to make the test wait for the promise to resolve correctly?