0

단위 테스트를하고자하는 매우 기본적인 공장 서비스가 있습니다. expect 문 앞에 $rootScope.$digest()$rootScope.$apply()을 시도했지만 단위 테스트에서 성공 또는 실패 처리기를 전혀 호출하지 않았습니다.하지만이 팩토리를 사용하는 컨트롤러의 컨텍스트에서 앱에서 정상적으로 호출됩니다.

example.service.js :

(function (angular) { 
    'use strict'; 

    angular 
    .module('exampleModule') 
    .factory('ExampleApi', ExampleApi); 

    ExampleApi.$inject = ['$http']; 
    function ExampleApi($http) { 
    return { 
     get: getExampleData 
    } 

    function getExampleData() { 
     return $http.get('example-endpoint'); 
    } 
    } 

})(angular); 

example.service.spec.js는

'use strict'; 

describe('Example API service', function() { 
    var $httpBackend; 
    var $rootScope; 
    var ExampleApi; 

    beforeEach(module('exampleModule')); 

    beforeEach(inject(
    function(_$httpBackend_, _$rootScope_, _ExampleApi_) { 
     $httpBackend = _$httpBackend_; 
     $rootScope = _$rootScope_; 
     ExampleApi = _ExampleApi_; 
    })); 

    it('calls the success handler on success', function() { 
    $httpBackend 
     .expectGET('example-endpoint') 
     .respond(200); 

    var handlerStubs = { 
     success: function() { 
     console.log("success called"); 
     }, 
     failure: function() { 
     console.log("failure called"); 
     } 
    } 

    spyOn(handlerStubs, 'success').and.callThrough(); 
    spyOn(handlerStubs, 'failure').and.callThrough(); 
    ExampleApi.get().then(handlerStubs.success, handlerStubs.failure); 
    //$rootScope.$digest(); 
    $rootScope.$apply(); 
    expect(handlerStubs.failure.calls.count()).toEqual(0); 
    expect(handlerStubs.success.calls.count()).toEqual(1); 
    }); 
}); 
+3

,'시도'$ httpBackend.flush(); 그것은 바로 응답 (200)''후 작동하지만 그것을하지 않았다 @LukeHutton' –

+0

'ExampleApi.get()'문장 다음에 DID. 이를 답으로 쓰면 올바른 것으로 표시하겠습니다. 고마워요! ('response'라인 다음에,'Error : 플러시 요청이 없다! '라고했기 때문에'get()'후에 시도해 보았습니다.) – anjunatl

답변

1

$httpBackend 모의가 전화했을 때, 가져 오기를 해결하는 flush() 방법을 포함 요청을 통해 테스트중인 코드를 동기식 제어 할 수 있습니다. $httpBackend.flush();이 호출되면 예상 값 .expectGET이 확인됩니다.

From the Angular Docs: 응답 (200)`후

The $httpBackend used in production always responds to requests asynchronously. If we preserved this behavior in unit testing, we'd have to create async unit tests, which are hard to write, to follow and to maintain. But neither can the testing mock respond synchronously; that would change the execution of the code under test. For this reason, the mock $httpBackend has a flush() method, which allows the test to explicitly flush pending requests. This preserves the async api of the backend, while allowing the test to execute synchronously.