2015-01-07 94 views
0

我正在嘗試爲我的應用程序編寫單元測試。它包含http請求呼叫在我的情況。如何在單元測試中檢查http請求?

測試文件

'use strict'; 
describe('Controller: testCtrl', function() { 

    // load the controller's module 
    beforeEach(module('myApp')); 

    var testCtrl, scope, $httpBackend; 

    beforeEach(inject(function (_$controller_, _$rootScope_, _$httpBackend_, $cookies) { 
     scope = _$rootScope_.$new(); 
     $httpBackend = _$httpBackend_; 

     testCtrl = _$controller_('testCtrl', { 
      $scope: scope, 
     }); 
    })); 

    it("should return product data", function() { 
     $httpBackend.whenGET('/api/store/' + productID + '/products').respond([{ 
      //not sure what I should do next... 
     }]) 
    }) 

控制器文件

$http.get(('/api/store/' + productID + '/products').success(
      function(data) { 
      //the data could contain 10 objects with 10+ property within each object. 
      } 
     ); 

由於HTTP請求返回一個非常複雜的對象,我不知道怎麼寫我的測試。任何人都可以幫助我嗎?非常感謝!

回答

0

你認爲你的API正常工作,並且你想真正測試的是:

  • 沒有您的應用程序應該的網址作出反應?
  • 它會對數據進行任何處理嗎?

因此,在您的whenGET中返回一個模擬對象,併爲任何數據處理代碼提供足夠的細節。

0

就測試而言,您將不得不返回一個模擬對象響應。這就是說,你不需要用你的1000線模擬JSON來污染你的測試用例。只需將其保存在單獨的文件中,並使用karma-ng-json2js-preprocessor將其從whenGET中返回。

相關問題