2014-03-05 43 views
1

我想用QUnit来测试一个角度控制器。但是,控制器已经注入了一个Angular服务,该服务取决于$ http服务。请see this plunker。我试图将真正的服务注入控制器并提供模拟$ httpBackend,但它似乎并没有像我期望的那样工作。我究竟做错了什么?AngularJS和QUnit:测试控制器与服务依赖

控制器方法:

// This is the method I want to test, but it depends 
// on a method in the service I want to mock...or maybe 
// I need to inject the real service and mock $http? 
$scope.sayHi = function() { 
    FooService.getWord().then(function(word){ 
     $scope.foo = word; 
    }); 
}; 

服务:

app.service('FooService', ['$http', function($http){ 
    return { 
     getWord: function(){ 
      return $http.get('Word'); 
     } 
    }; 
}]); 

测试:

var injector = angular.injector(['ng', 'app']); 
    var http = injector.get('$httpBackend'); 
    var fService = injector.get('FooService'); 

    var init = { 
    setup: function() { 
     this.$scope = injector.get('$rootScope').$new(); 
     var $controller = injector.get('$controller'); 
     //var $service = injector.get('$service'); 

     // I don't know if I'm doing this correctly... 
     $controller('FooController', { 
      $scope: this.$scope, 
      // Trying to inject the real service here... 
      FooService: fService 
      // Trying to fake the service here... 
      //FooService: { 
      // getWord: function() { 
      // // how to return a fake promise? using $httpBackend?? 
      // return { 
      //  'then': function() { 
      //  return 'hi'; 
      //  } 
      // }; 
      // } 
      //} 
     }); 
    } 
    }; 

    module('Basic Controller Test', init); 

    test('service injected correctly', function(){ 
    ok(angular.isFunction(fService.getWord)); 
    }); 

    test('sayHi from service', function() { 
    http.expectGET('Word').respond('hi'); 

    // this is the method I'd like to test on the controller 
    this.$scope.sayHi(); 

    // after the async service call completes, it should set scope.foo === 'hi' 
    equal(this.$scope.foo, 'hi'); 
    }); 

谢谢,

安迪

回答

3

我做了一个plunker,这将提高你的测试:

http://plnkr.co/edit/tQBrHTMCU3IBEfUGGkWa?p=preview

你需要调用http.flush() HTTP调用之后。

+0

非常感谢你非常感谢!在控制器中,我只需引用word.data以使测试通过,因为它已被分配给响应对象。 – Andy

+0

没有问题。只有当你调用http.flush时,httpBackendService才会执行实际的调用,这就是你想知道的情况。 – ailveen

相关问题