我是角度开发的新手,我正在尝试学习如何测试角度控制器。我正在测试的控制器使用$ location.seach()。我查看了$ location的文档,但是很快就看不出我应该如何在karma / jasmine中嘲笑它。
控制器:
rmtg.controller('ErrorCtrl', ['Session', '$location', '$routeParams', '$scope', '$window',
function(Session, $location, $routeParams, $scope, $window) {
console.log('ErrorCtrl(%o, %o, %o)', $location.path(), $location.search(), $routeParams);
$scope.status = $location.search().status;
$scope.message = $location.search().message;
$scope.isAuthorized = (typeof(Session.auth) === 'object');
$scope.signin = function() {
$window.location = '/signin/#/' + $routeParams.origin + (Session.auth ? '?email=' + Session.auth.email : '');
};
}]);
我当前的规范尝试:
'user strict';
describe('Testing the errorCtrl controller', function(){
beforeEach(module("rmtg"));
var errorCtrl, scope;
beforeEach(inject(function($controller, $rootScope){
scope = $rootScope;
errorCtrl = $controller("ErrorCtrl", {
$scope: scope
});
}));
it('$scope.status should be set to 404 when location is set to 404', function(){
//set the $location.search values so that the scope is correct
$location.search('status', '404');
expect(scope.status).toBe('404');
});
});
当前的错误消息: 当location设置为404 FAILED时,测试errorCtrl控制器$ scope.status应该设置为404 预计未定义为' 404'。 在对象。 (/Users/adamremeeting/git/mrp-www/app/tests/example.js:20:24)
我也非常感谢使用angular 1.5的tdd上的资源链接以及我如何正确地模拟和存根。
回答后编辑
所以我根据user2341963的建议更新了测试,并尽力浏览他的plunker示例,但仍然没有通过测试。
当前规范(控制器没有从上面改变)
'user strict';
describe('ErrorCtrl', function(){
beforeEach(module("rmtg"));
var scope, $location, $controller;
beforeEach(inject(function(_$controller_, _$rootScope_, _$location_){
scope = _$rootScope_.$new();
$location = _$location_
$controller = $_controller_;
}));
describe('$scope.status', function(){
it('should set status to 404', function(){
//set the $location.search values so that the scope is correct
$location.search('status', '404');
//init controller
$controller('ErrorCtrl', {
$scope: scope,
$location: $location
});
expect(scope.status).toBe('404');
});
});
});
但是我现在因为没有定义$ controller 而收到错误。
答案 0 :(得分:3)
您的测试中出现undefined
,因为您没有在任何地方设置$location
。
根据您的控制器,必须在初始化控制器之前设置搜索参数。有关完整示例,请参阅plunker。
describe('testApp', function() {
describe('MainCtrl', function() {
var scope, $location, $controller;
beforeEach(module('myApp'));
beforeEach(inject(function(_$rootScope_, _$controller_, _$location_) {
scope = _$rootScope_.$new();
$location = _$location_;
$controller = _$controller_;
}));
it('should set status to 404', function() {
// Set the status first ...
$location.search('status', '404');
// Then initialise the controller
$controller('MainCtrl', {
$scope: scope,
$location: $location
});
expect(scope.status).toBe('404');
});
});
});
至于资源,到目前为止我发现angular docs足够好了。