2013-10-18 143 views
1

我測試的angularjs控制器,使用也嘲笑,但它引發的錯誤「錯誤:Unsatisfied requests: POST /myurl測試:unsatistifed POST請求

我的測試文件中包含一個beforeEach方法這樣

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


    scope = $rootScope.$new(); 
    MainCtrl = $controller('MyCtrl', { 
     $scope:scope 
    }); 

和我的測試情況是:

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) 

    }) 

的方法saveNewPage樣子:

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')永遠不會執行(在業力控制檯它從來沒有打印)。

編輯: 與此同時,我正在研究有關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) 


    }) 

但現在它提出了Error: No response defined !,就像如果我沒有指定該URL

+0

您可以嘗試用'existingPage:p'替換'existingPage:new Object(pages [0])'嗎? – Andyrooger

回答

-1

假設POST是從何而來saveNewPage模擬,您需要撥打電話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響應相關聯