【发布时间】: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