2016-04-06 14 views
0

Beispiel Test eine verzögerte Versprechen lösen fälschen:Wie simuliere ich eine Verzögerung mit Chai-as-versprochen und Karma/eckig?

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 
    }); 

});

Die readme sagt zu tun:

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

Der Fehler, den ich bekommen ist:

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. 
+0

Wie wäre es damit? triggert 'done()' Callback mit '.notify (done);' –

Antwort

0

Der $timeout Dienst gibt bereits ein Versprechen. Keine Notwendigkeit, einen herzustellen.

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

In diesem Beispiel wird fakePromise auf ein Versprechen gesetzt, die nach 100 Millisekunden zu "foo" aufgelöst wird.