Ken*_*nne 19 unit-testing jasmine angularjs
如何测试具有解析属性的控制器?它抛出一个错误:未知提供者:InitProvider,在测试期间,可以理解.我该怎么测试呢?
我在路由配置中使用init属性来加载数据并在控制器实例化时将其传递给控制器,这样在加载数据之前路由不会改变.
$routeProvider
.when('/topic/:topic_id/content/:content_id', {
templateUrl: 'views/content.html',
controller: 'ContentCtrl',
resolve: {
init: ContentCtrl.init
}
});
Run Code Online (Sandbox Code Playgroud)
这种模式首先是完全错误的吗?
'use strict';
var ContentCtrl = ['$scope', '$location', '$routeParams', 'init', function ($scope, $location, $routeParams, init) {
$scope.contents = init.contents;
}];
ContentCtrl.init = ['$q', 'app_config', '$log', '$timeout', function ($q, app_config, $log, $timeout) {
var defer = $q.defer();
$log.log("ContentCtrl loading..");
$timeout(function() {
defer.resolve({contents: [
{message: 'Hello!'}
]});
$log.log("ContentCtrl loaded.");
}, 2000);
return defer.promise;
}];
angular.module('studentportalenApp').controller('ContentCtrl', ContentCtrl);
Run Code Online (Sandbox Code Playgroud)
我想将整个控制器封装在内部.controler('ContentCtrl', function() { ... }),但尚未弄清楚如何正确完成这一操作以使init在路由配置中可用.
小智 26
在这里遇到同样的事情.我使用这里的方法解决了它:https://groups.google.com/forum/?fromgroups =#!topic/angular/LzXm-9nwkjY.
基本上,我模拟了通常使用简单变量发送的数据,并将其添加到测试中的控制器中.在你的情况下,我认为它看起来像:
var initData = {
contents: [{message: 'Hello!'}]
};
$controller("ContentCtrl", { $scope: ..., init: initData });
Run Code Online (Sandbox Code Playgroud)
最终通过将所有内容转换为服务来解决,正如charlietfl所建议的那样.
例:
路线配置:
//This helper injects a function with the service
//defined in the initMethod string and returns services.prepare()
var interceptWith = function(initMethod) {
return [initMethod, function(m) {
return m.prepare();
}];
}
$routeProvider
.when('/foobar/', {
templateUrl: 'foobar.html',
controller: 'FoobarCtrl',
resolve: {
init: interceptWith('FoobarCtrlInit')
}
});
Run Code Online (Sandbox Code Playgroud)
foobar控制器定义:
angular.module('fooApp').controller('FoobarCtrl', ['$scope', 'init', function ($scope, init) {
$scope.data = init.data;
}])
.service('FoobarCtrlInit', ['$q', '$timeout', function ($q, $timeout) {
var _prepare = function() {
var deferred = $q.defer();
//Fake async loading of data
$timeout(function() {
deferred.resolve({data: ['A','B','C']});
}, 1000);
return deferred.promise;
}
return {
prepare: _prepare
}
}]);
Run Code Online (Sandbox Code Playgroud)
要测试这个,可以这样做:
'use strict';
describe('Controller: FoobarCtrl', function() {
// load the controller's module
beforeEach(module('fooApp'));
var FoobarCtrl,
scope;
// Initialize the controller and a mock scope
beforeEach(inject(function($controller) {
scope = {};
CourseCtrl = $controller('FoobarCtrl', {
$scope: scope,
init: {data: ['Testdata A', 'B', 'C']}
});
}));
it('should attach a list of data to the scope', function() {
expect(scope.data.length).toBe(3);
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9825 次 |
| 最近记录: |