2014-10-11 4 views
0

각도 약속을 사용하여 몇 가지 재스민 테스트를하고 타이밍 관련 질문이 있습니다. 대답은 Unit-test promise-based code in Angular이지만이 작동 방식에 대한 설명이 필요합니다. then 메서드는 항상 비동기 방식으로 처리되므로 다음 테스트가 어떻게 통과되는지 보장됩니다. expect이 실행중인 then 블록보다 먼저 실행되고 값이 할당되기 전에 expect가 실행될 위험이 없습니까? 또는 ... 다이제스트주기는 예상이 실행되기 전에 값이 할당되도록 보장합니다. 즉, 다이제스트주기는 코드가 진행되도록 허용되기 전에 약속이 모두 해결된다는 것을 보장하는 차단 호출처럼 효과적으로 작동합니다.약속을 사용하여 재스민 비동기 테스트

function someService(){ 
    var deferred = $q.defer(); 
    deferred.resolve(myObj); 
    return deferred.promise; 
} 

it ('testing promise', function() { 
    var res; 
    var res2; 
    someService().then(function(obj){ 
    res = "test"; 
    }); 

    someService().then(function(obj){ 
    res2 = "test2"; 
    }); 

    $rootScope.$apply(); 
    expect(res).toBe('test'); 
    expect(res2).toBe('test2'); 
}); 

답변

1

다이제스트주기 효과적으로 코드가 수행되도록 허용되기 전에 약속을 모두 해결하는 것을 보장 차단 호출처럼 동작합니다.

그래, 정확하게 말하면 해결 된 약속의 성공 콜백이 실행되었음을 보증합니다.

이있는 올바른 생각에 마이클의 대답 포인트는 여기에 키가 $apply()가 적절한 범위에서 호출이다 example that shows how the digest cycle is tied to the success callbacks of promises in the docs for $q

+0

좋은 답변입니다. 감사! – user4131376

0

동안 매우 유사합니다. 다음은 각도 문서의 예입니다.

it('should simulate promise', inject(function($q, $rootScope) { 
    var deferred = $q.defer(); 
    var promise = deferred.promise; 
    var resolvedValue; 

    promise.then(function(value) { resolvedValue = value; }); 
    expect(resolvedValue).toBeUndefined(); 

    // Simulate resolving of promise 
    deferred.resolve(123); 
    // Note that the 'then' function does not get called synchronously. 
    // This is because we want the promise API to always be async, whether or not 
    // it got called synchronously or asynchronously. 
    expect(resolvedValue).toBeUndefined(); 

    // Propagate promise resolution to 'then' functions using $apply(). 
    $rootScope.$apply(); 
    expect(resolvedValue).toEqual(123); 
})); 
+0

정확하다고 생각하지 않습니다. '$ apply '라고 부르는 범위에 따라 동작에 차이가있는 것은 아닙니다. 그러나'$ digest'의 동작은 어떤 범위에 의존합니다. –