2013-10-18 6 views
1

내가 AngularJS와 컨트롤러를 테스트도 사용하고는 조롱,하지만 오류 '오류가 발생합니다 : Unsatisfied requests: POST /myurl 시험에 대한 나의 파일이시험 : unsatistifed POST 요청

httpBackend.whenPOST('/myurl') 
    .respond(200,obj1); 
    httpBackend.expectPOST('/myurl') 


    scope = $rootScope.$new(); 
    MainCtrl = $controller('MyCtrl', { 
     $scope:scope 
    }); 
같은 beforeEach 방법을 포함

내 테스트 케이스는 다음과 같습니다

: 방법 saveNewPage의 모습

it('scope.mymethod should work fine', function(){ 

     httpBackend.flush() 


     // verify size of array before calling the method  
     expect(scope.myobjs.length).toEqual(2) 
     // call the method 
     scope.saveNewPage(myobj) 
     // verify size of array after calling the method 
     expect(scope.myobjs.length).toEqual(3) 

    }) 

function saveNewPage(p){ 
    console.log('Hello') 
    $http.post('/myurl', { 
       e:p.e, url:p.url, name:p.name 
      }).then(function (response) { 
        otherMethod(new Page(response.data.page)) 
       }, handleError); 
} 

console.log('Hello')은 절대로 실행되지 않습니다 (카르마 콘솔에서는 결코 인쇄되지 않습니다).

EDIT : 한편 httpBackend에 관한 문서를 연구 중이므로 httpBackend.flush()의 위치를 ​​변경하려고했습니다. 기본적으로, 첫 번째 flush()를 실행하여 범위의 데이터를 초기화 한 다음 메서드를 실행 한 다음 보류중인 요청에 대해 다른 flush()를 실행합니다. 특히,이 상황에서 테스트 케이스의 모양 :

it('scope.saveNewPage should work fine', function(){ 
     var p=new Object(pages[0]) 

     httpBackend.flush() 

     httpBackend.whenPOST('/myurl',{ 
      url:pages[0].url, 
      existingPage:new Object(pages[0]), 
      name:pages[0].name 
     }).respond(200,{data:pages[0]}) 
     httpBackend.expectPOST('/myurl') 

     scope.saveNewPage(p) 

     httpBackend.flush() 


     expect(scope.pages.length).toBe(3) 


    }) 

하지만 지금은 내가 그 URL에서 POST가 saveNewPage에서 오는하도록되어 가정

+0

'existingPage : new Object (pages [0])'를'existingPage : p'로 바꿀 수 있습니까? – Andyrooger

답변

-1

에 대한 모의를 지정하지 않은 경우처럼, Error: No response defined ! 제기, httpBackend.flush()saveNewPage과 그 결과를 조사하는 라인 사이에서 호출해야합니다. flush은 코드에서 이미 요청한 응답 만 플러시합니다.

it('scope.mymethod should work fine', function(){ 
    expect(scope.myobjs.length).toEqual(2) 
    scope.saveNewPage(myobj) 
    expect(scope.myobjs.length).toEqual(2) 

    httpBackend.flush() 
    expect(scope.myobjs.length).toEqual(3) 
}) 
+0

작동하지 않습니다. 이런 방식으로'예기치 않은 요청'을 제기합니다. –

+0

'saveNewPage' 함수는 어떻게 생겼습니까? – Andyrooger

+0

saveNewPage 메소드를 포함하여 질문을 편집했습니다. –

0

내가 이런 식으로 해결 :

  • 내가 테스트 할 메서드를 호출하기 전에 whenPOST 및 expectPOST의 전화를 넣어
  • 내가 테스트하는 방법을 호출 한 후() httpBackend.flush를 넣어, 그래서 보류중인 요청을 생성하는 메소드를 호출하고, httpBackend.flush()에 의해 보류중인 요청을 만족시킨다.
  • respond 메소드의 매개 변수를 조정했다. 기본적으로 응답의 data 키에 대한 응답을 연결할 필요가 없습니다.