2014-11-05 3 views
1

모카를 처음 사용하지만 약속을 지원한다고 읽었지만 내 문제를 해결하는 문서를 찾지 못하는 것 같습니다. 약속을 반환하는 authenticate 메서드가 있습니다. 내 시험에서 통과/실패하기 위해 끝날 때까지 기다려야합니다. 여기 모카와 함께 약속을 반환하는 테스트 메서드 호출

(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

당신은'done' 매개 변수를'it'에 받아 들여야하고, 다른 비동기 테스트처럼 끝날 때 실행해야합니다. –

+0

@ 케빈 B, 예가 있습니까? – Boone

+1

http://mochajs.org/#asynchronous-code 해당 부분의 끝 부분에있는 코드를 메모하면 간단히 약속 자체를 반환 할 수 있습니다. –

답변

3

각도 약속은 다음 소화주기까지 해결되지 않습니다 감사합니다.

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

빠르게 때 단위 테스트 각도 응용 프로그램으로 실행할 수 있습니다

한 가지 범위를 통해 (특정 상황에서 다이제스트주기를 손으로 크랭크 할 필요가 $ 적용(). 또는 scope. $ digest()). 불행하게도 이러한 상황 중 하나 인 은 매우 분명하지 않은 약속 된 해결 방법입니다. 처음부터 각도 개발자.

$rootScope.$apply()을 추가하면 비동기 테스트가 필요하지 않고 문제를 해결하고 약속을 해결해야합니다.

관련 문제