2014-03-05 39 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

相關問題