Javascript 如何在angular中测试从angular服务获取数据的控制器?
非常简单,我有一个控制器,它在服务的作用域上设置了一个属性 控制器:Javascript 如何在angular中测试从angular服务获取数据的控制器?,javascript,angularjs,jasmine,Javascript,Angularjs,Jasmine,非常简单,我有一个控制器,它在服务的作用域上设置了一个属性 控制器: dadApp.controller('landingController', function($scope, automationService) { $scope.hello = "from controller"; $scope.foo = automationService.foo; // load data from service. }); 服务: dadApp.factory('aut
dadApp.controller('landingController', function($scope, automationService) {
$scope.hello = "from controller";
$scope.foo = automationService.foo;
// load data from service.
});
服务:
dadApp.factory('automationService', function($http) {
var _foo = [];
$http.get('/api/automation')
.then(function(result) {
angular.copy(result.data, _foo);
},
function() {
alert('error');
});
return {
foo: _foo
};
});
在我的规范/测试文件中,如何测试此控制器,因为它依赖于服务?(仅供参考,该服务是ASP.NET WebAPI 2
以下是我的规格:
/// <reference path="../Scripts/angular.js" />
/// <reference path="../Scripts/angular-mocks.js" />
/// <reference path="../Scripts/angular-resource.js" />
/// <reference path="../Scripts/angular-route.js" />
/// <reference path="../app/app.js" />
/// <reference path="../app/services/automationService.js" />
/// <reference path="../app/controllers/landingController.js" />
'use strict';
var scope, ctrl;
describe('DAD tests', function() {
beforeEach(module('dadApp'));
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('landingController', { $scope: scope });
}));
describe('landing controller tests', function() {
describe('scope.hello', function() {
it('should equal "from controller"', function() {
expect(scope.hello).toEqual("from controller");
});
});
});
});
//
///
///
///
///
///
///
"严格使用",;
var作用域,ctrl;
描述('DAD测试',函数(){
在每个(模块(‘dadApp’)之前;
beforeach(注入函数($controller,$rootScope){
scope=$rootScope.$new();
ctrl=$controller('landingController',{$scope:scope});
}));
描述(‘着陆控制器测试’,功能(){
描述('scope.hello',function()){
它('应该等于'from controller',function(){
expect(scope.hello).toEqual(“来自控制器”);
});
});
});
});
可能是这样的:
var mockedFoo = {
bar: true,
baz: 123,
other: "string"
};
var automationServiceMock = {
foo: function() {
return mockedFoo;
}
};
describe('DAD tests', function() {
beforeEach(module('dadApp'));
beforeEach(inject(function($controller, $rootScope) {
scope = $rootScope.$new();
ctrl = $controller('landingController', {
$scope: scope,
automationService: automationServiceMock
});
}));
describe('landing controller tests', function() {
describe('scope.hello', function() {
it('should equal "from controller"', function() {
expect(scope.hello).toEqual("from controller");
});
});
});
});
你应该模拟你的automationService并将模拟注入你的控制器,就像你对你创建的示波器所做的那样。谢谢@aet,这也是我的想法。你有一个模拟服务并在jasmine中使用它的片段吗?我们最终使用了多种技术,我提供的答案只是一种方法。你也可以使用jasmine spyOn,根据模仿工作的复杂程度,这可能会更容易。