0

Example test faking a delayed promise resolve:

describe('Example', function() {
  var $q;
  var $rootScope;
  var $scope;
  var $timeout;
  var fakePromise;

  beforeEach(inject(function (_$q_, _$rootScope_, _$timeout_) {
    $q = _$q_;
    $rootScope = _$rootScope_;
    $timeout = _$timeout_;
    $scope = $rootScope.$new();

    fakePromise = function (){
      return new Promise(function(resolve, reject){
        $timeout(function(){
          resolve('foo');
        }, 100);
      });
    };
  }));

  afterEach(function () {
    $scope.$apply();
  });

  it('should wait for promise to resolve and have a result', function(){
    return fakePromise().should.eventually.equal('foo'); //taken from chai-as-promised readme
  });

});

The readme says to do:

return doSomethingAsync().should.eventually.equal("foo");

The error I get is:

Chrome 49.0.2623 (Mac OS X 10.11.4) Example should wait for promise to resolve and have a result FAILED
  Error: timeout of 2000ms exceeded. Ensure the done() callback is being called in this test.
chovy
  • 72,281
  • 52
  • 227
  • 295

1 Answers1

0

The $timeout service already returns a promise. No need to manufacture one.

fakePromise = $timeout(function() {return "foo"}, 100);

In this example, fakePromise is set to a promise that resolves to "foo" after 100 milliseconds.

georgeawg
  • 48,608
  • 13
  • 72
  • 95