2016-06-22 8 views
3

나는 karma + jasmine을 사용하여 서비스 약속을 테스트하는 방법을 알아 냈지만 성공하지는 못했습니다. 지금까지 내가 결과 오류가 무슨 짓을 :angularjs 1 and jasmine, 서비스 약속 테스트

PhantomJS 2.1.1 (Mac OS X 0.0.0) The FetchData service should fetch data FAILED 
    Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL. 

fetchData 서비스 :

module.exports = function($http) { 
    return { 
     getFoo: function(id) { 
      return $http.get('https://api/' + id) 
         .then(function(result) { 
          return result.data; 
         }); 
     } 
    } 
}; 

테스트 : 나는 그것을 할 수 누락 될 수 있습니다 뭔가가 있는지 궁금

describe('The FetchData service', function() { 

    var dataFetcher; 

    beforeEach(angular.mock.module("myApp")) 

    beforeEach(inject(function(_dataFetcher_) { 
    dataFetcher = _dataFetcher_; 
    })); 

    it('should fetch data', function(done) { 

    var testData = function(res) { 
     expect(res.success).toBe(true); 
    }; 

    var failTest = function(error) { 
     expect(error).toBeUndefined(); 
    }; 

    dataFetcher.getFoo(id) 
     .then(testData) 
     .catch(failTest); 

    }); 
}); 

이걸 이해하도록 도와주세요.

고마워요!

+0

https://docs.angularjs.org/api/ngMock/service/$httpBackend – Phil

답변

1

$ http 서비스를 조롱하기 위해 테스트에 $ httpBackend 서비스를 삽입해야합니다.

그러면 실제 HTTP 호출을 조롱하기 위해 $ httpBackend.flush를 호출해야합니다. 예를 들어 각도 문서를 확인하십시오.

편집 :

it('should fetch data', function() { 

    var status, data; 
    function successCB(response){ 
    status = 'success'; 
    data = response.data; 
    } 
    function errorCB(){ 
    status = 'error' 
    } 
    //only pass the success and error callbacks here 
    dataFetcher.get(1).then(successCB, errorCB); 

    // you need to stop it  
    $httpBackend.flush(); 

    //assert for success 
    $httpBackend 
    .when('GET', 'https://api/1') 
    .respond(200, {foo:'bar'}); 

    expect(status).toEqual('success'); 
    expect(data).toEqual({foo: 'bar'}); 

    //assert for error 
    $httpBackend 
    .when('GET', 'https://api/1') 
    .respond(500, 'An error has occured.'); 

    expect(status).toEqual('success'); 

}); 
0

이 실제 AngularJS와 문서를 기반으로 내가 지금까지이있어 솔루션입니다.

describe('The FetchData service', function() { 

    var dataFetcher, $httpBackend; 

    beforeEach(angular.mock.module("myApp")); 

    beforeEach(inject(function(_dataFetcher_, _$httpBackend_) { 
     dataFetcher = _dataFetcher_; 
     $httpBackend = _$httpBackend_; 
    })); 

    afterEach(function() { 
     $httpBackend.verifyNoOutstandingExpectation(); 
     $httpBackend.verifyNoOutstandingRequest(); 
    }); 

    it('should fetch data', function() { 

     var status, data, 
      pid = 2140, 
      api = 'https://api'; 

     function successHandler(res){ 
      status = 'success'; 
      data = res.data; 
      expect(res.success).toEqual(true); 
      expect(status).toEqual('success'); 
     } 

     function errorHandler(){ 
      status = 'error' 
     } 

     $httpBackend 
     .when('GET', api + '/' + pid) 
     .respond({ success: true }); 

     $httpBackend 
     .when('GET', api + '/' + pid) 
     .respond(500, 'An error has occured.'); 

     dataFetcher.get(pid).then(successHandler, errorHandler); 

     $httpBackend.flush(); 

    }); 

}); 
+0

귀하의 솔루션이 올 것 같다

나는 그것이 자기 설명 (@의 mehndra의 대답과 팁에 기반 업데이트) 희망 하지만 당신의 주장은 그보다 조금 나아질 수 있다고 생각합니다. 테스트에서 서비스 호출에서 성공 및 오류 처리기를 전달한 다음 호출 된 핸들러를 확인할 수 있습니다. 그 다음 콜백에서 단언 문안을 피하고 싶습니다. –

+0

@MahendraSingh 마음은 모범을 보이고 있습니까? – punkbit

+0

수정 사항을 확인하십시오. –

관련 문제