2014-11-05 112 views
1

我是摩卡新手,但我看過他們支持諾言,但我似乎無法找到解決我的問題的任何文檔。我有一個驗證方法返回一個承諾。在我的測試中,我需要等到完成才能通過/失敗。用摩卡返回承諾的測試方法調用

這裏是我的身份驗證工廠:

(function() { 
'use strict'; 

angular.module('app.authentication').factory('authentication', authentication); 

/* @ngInject */ 
function authentication($window, $q, $location, authenticationData, Session) { 
    var authService = { 
     authenticate: authenticate 
    }; 

    return authService; 

    function authenticate() { 
     var token = authenticationData.getToken(); 
     var deferral = $q.defer(); 
     if (!Session.userId && token) { 
      authenticationData.getUser(token).then(function(results) { 
       Session.create(results.id, results.userName, results.role); 
       deferral.resolve(); 
      }); 
     } 
     else{ 
      deferral.resolve(); 
     } 

     return deferral.promise; 
    }......... 

這裏是我的測試:

describe('authentication', function() { 

    beforeEach(function() { 
     module('app', specHelper.fakeLogger); 
     specHelper.injector(function($q, authentication, authenticationData, Session) {}); 
    }); 

    beforeEach(function() { 
     sinon.stub(authenticationData, 'getUser', function(token) { 
      var deferred = $q.defer(); 
      deferred.resolve(mockData.getMockUser()); 
      return deferred.promise; 
     }); 
    }); 

    describe('authenticate', function() { 
     it('should create Session with userName of TestBob', function() { 
      authentication.authenticate().then(function(){ 
       console.log('is this right?'); 
       expect(Session.userName).to.equal('TesaatBob'); 
      }, function(){console.log('asdfasdf');}); 
     }); 
    }); 
}); 

當我運行此,測試通過,因爲它永遠不會使它的承諾里,從來沒有碰到期待。如果我把「return authenication.authenticate ....」,那麼它超時錯誤。

謝謝

+0

您需要爲'it'接受'done'參數,然後在完成後執行它,就像其他任何異步測試一樣。 – 2014-11-05 19:06:19

+0

@凱文B,你有沒有例子? – Boone 2014-11-05 19:22:15

+1

http://mochajs.org/#asynchronous-code注意該部分末尾的代碼,您可以簡單地返回承諾本身。 – 2014-11-05 19:23:17

回答

3

直到下一個摘要循環才能解決角度承諾。

http://brianmcd.com/2014/03/27/a-tip-for-angular-unit-tests-with-promises.html

,你很快就會碰到單元測試角 應用程序時

有一兩件事是需要手搖在某些情況下, 消化週期(通過範圍$適用()。或範圍$ digest())。不幸的是,這些情況中的一個 是諾言解決方案,這對於開始Angular開發人員來說不是非常明顯的 。

我相信增加一個$rootScope.$apply()應該可以解決您的問題並強制承諾解決方案,而不需要異步測試。

相關問題