繁体   English   中英

使用Jasmine进行单元测试$ http

[英]Unit Testing $http using Jasmine

我应该使用茉莉花模拟ajax调用。

以下是我的代码段。

var httpBackend;
var http;

beforeEach(inject(function ($injector) {
    $httpBackend = $injector.get('$httpBackend');
    scope = $injector.get('$rootScope').$new();
    var $controller = $injector.get('$controller');
    var MainCtrl = $controller('scanningClientsController',
        { $scope: scope });
}));

   it("Verify Ajax Call", function () {    
    var test;
    $httpBackend.expectGET(scope.requestUrl).respond([{}, {}, {}]);      
    scope.GetClients().then(function (response) {
        test = response;
    });
    $httpBackend.flush(); 
    expect(test.length).toBe(3);

我在控制器中的功能如下:

  $scope.GetClients =
         function () {
             $http({
                 method: 'GET',
                 url: $scope.requestUrl,
             }).success(function (response, status, headers, config) {
                 $scope.scanningClientsList = response.data;

             }).error(function (data, status, headers, config) {

             });
         };

现在我得到一个错误

TypeError: 'undefined' is not an object (evaluating 'scope.GetClients().then')

尝试从此http://chutzpah.codeplex.com/workitem/230修复

但这似乎无法解决问题。 有任何想法吗?

您还需要注入$ httpBackend:

$httpBackend = $injector.get('$httpBackend');

编辑

你是不是在你返回承诺$scope.GetClients功能,所以你实际上是在呼吁then为undefined ..

尝试这样的事情:

 $scope.GetClients =
     function () {
         var deferred = $q.defer();
         $http({
             method: 'GET',
             url: $scope.requestUrl,
         }).success(function (response, status, headers, config) {
             $scope.scanningClientsList = response.data;
             deferred.resolve(response.data);

         }).error(function (data, status, headers, config) {
             deferred.reject(data);
         });
         return deferred.promise;
     };

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM