2017-09-05 9 views
0

각진 앱에 대한 단위 테스트를 작성하는 중 예기치 않은 결과가 발생했습니다. 예기치 않은 행동을 샘플 테스트로 응축 할 수있었습니다.실패한 어설 션이 약속 잡기를 유발하는 이유는 무엇입니까?

그 다음 블록에서 should.equal(true, false, 'should then') 어설 션 오류는 약속의 catch 블록을 트리거하는 것으로 보입니다. 나는이 테스트를 실행하면

describe.only('test', function() { 
    var $q, $rootScope; 
    beforeEach(function() { 
    inject(function(_$q_, _$rootScope_) { 
     $q = _$q_; 
     $rootScope = _$rootScope_.$new(); 
    }); 
    }); 


    var stubService = sinon.stub(service, 'getPanel'); 

    it('shall...', function() { 
    //1 
    $q.when().then(function() { 
     console.log('log then') 
     should.equal(true, false, 'should then') //<---assertion fails 
    }).catch(function() { 
     console.log('log catch') //<--- why does this block run? 
     should.equal(true, false, 'should catch') 
    }) 
    $rootScope.$apply(); //wait for promises to finish 

    }); 
}); 

출력은 다음과 같습니다

LOG LOG: 'log then' 
LOG LOG: 'log catch' 

    test 
    ✗ shall... 
    should catch: expected true to equal false 

내가 예상 :

LOG LOG: 'log then' 

    test 
    ✗ shall... 
    should then: expected true to equal false 

내가 예상 결과를 얻을이 스타일을 사용하는 경우 :

$q.when().then(function() { 
    console.log('log then') 
    should.equal(true, false, 'should then') 
}, function() { 
    console.log('log catch') 
    should.equal(true, false, 'should catch') 
}) 

우리 회사의 관례는 전나무 t 스타일을 사용하므로 가능한 경우 첫 번째 스타일을 사용하고 싶습니다.

답변

1

관찰하고있는 동작에 대한 한 가지 설명은 조건이 충족되지 않을 경우 어설 션이 실제로 후드 아래 throws an error 인 것을 나타냅니다.

핸들러 기능 (onFulfilled 또는 onRejected) 다음 (즉시 스택이 비어로) 비동기 적으로 호출됩니다 :

당신이 $q를 사용하고 있지만, 나는 강조 광산이 documentation on Promise behaviour 여전히 적용 믿습니다. 핸들러 함수 호출 후, 핸들러 함수 : 이 오류를 던집니다. 반환 된 약속은 던져진 오류와 함께 거부되고 값은입니다.

따라서 사건에 의해 발생 should.equal 오류가 거부 값이 발생되는 에러으로 실행하도록 할 catch 대한 코드 블록시킨다.