Promise Testing

by lucasprus

HTML

<script src="http://sukima.github.com/jasmine-all/jasmine-all-min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.15/angular.min.js"></script>
<script src="http://code.angularjs.org/1.2.15/angular-mocks.js"></script>

JavaScript

describe('how to test with promises', function () {
  var deferred, $rootScope;

  beforeEach(function () {
    inject(function ($q, _$rootScope_) {
      $rootScope = _$rootScope_;
      deferred = $q.defer();
    });
  });

  it('does a thing one way', function () {
    deferred.promise.then(function (value) {
      expect(value).toBe(4);
    });
    deferred.resolve(10);
    $rootScope.$digest();
  });

  it('does a thing another way', function () {
    var handler = jasmine.createSpy('success');
    deferred.promise.then(handler);
    deferred.resolve(10);
    $rootScope.$digest();
    expect(handler).toHaveBeenCalledWith(4);
  });
});