2015-01-07 174 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中返回。

相关问题