【问题标题】:AngularJS and QUnit: Testing Controller with Service DependencyAngularJS 和 QUnit:使用服务依赖测试控制器
【发布时间】:2014-03-05 22:35:58
【问题描述】:

我正在尝试使用 QUnit 来测试 Angular 控制器。然而,控制器注入了一个 Angular 服务,该服务依赖于 $http 服务。请see this plunker。我正在尝试将真正的服务注入控制器并提供模拟 $httpBackend,但它似乎没有像我预期的那样工作。我做错了什么?

控制器方法:

// 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');
  });

谢谢,

安迪

【问题讨论】:

    标签: angularjs unit-testing qunit


    【解决方案1】:

    我做了一个 plunker 可以改进你的测试:

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

    您需要在 http 调用后调用 http.flush()

    【讨论】:

    • 太棒了,非常感谢!在控制器中,我只需要引用 word.data 即可使测试通过,因为它被分配给了一个响应对象。
    • 没有问题。只有当您调用 http.flush 时,实际的调用才会由 httpBackendService 执行,这就是它的用途,以防您想知道。
    猜你喜欢
    • 2013-06-11
    • 2016-05-03
    • 2013-06-02
    • 2012-10-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多