2016-04-06 31 views
0

實施例測試僞造延遲承諾決心:如何模擬一個延遲與chai-as-promised和業力/角?

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

});

自述說做:

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

我得到的錯誤是:

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

這個怎麼樣?用'.notify(done)'觸發'done()'回調。' –

回答

0

$timeout服務已返回一個承諾。不需要製造一個。

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

在這個例子中,fakePromise被設定爲後100毫秒解析爲「foo」的一個承諾。