【发布时间】:2016-11-22 16:50:40
【问题描述】:
我有一个简单的登录控制器:
'use strict';
angular.module('login', ['ngRoute'])
.config(['$routeProvider', function ($routeProvider) {
}])
.controller('LoginCtrl', ["$scope", "$route", "LoginService", function ($scope, $route, LoginService) {
var self = this;
this.showGuestLogin = true;
this.showUserLogin = false;
this.toggleUserLoginType = function () {
this.showGuestLogin = !this.showGuestLogin;
this.showUserLogin = !this.showUserLogin;
}
this.submitGuestLogin = function()
{
if(this.guestName === undefined || this.guestName.trim() == '')
{
self.loginError = "Name cannot be blank";
return;
}
LoginService.loginAsGuest(this.guestName.trim())
.then(function()
{
self.loginError = null;
$route.reload();
})
.catch(function(err)
{
self.loginError = 'An error occured. Please try again';
});
}
}]);
我正在尝试使用:
describe('LoginCtrl', function()
{
beforeEach(module('login'));
var ctrl;
beforeEach(inject(function($controller)
{
ctrl = $controller('LoginCtrl');
}));
it('should set error if guest name is undefined', function(done)
{
ctrl.guestName = undefined;
ctrl.submitGuestLogin();
expect(ctrl.loginError).toBeDefined();
});
});
但是当测试运行时我在控制台中收到这个错误
错误:[$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope%20%3C-%20LoginCtrl
我可以在 karma 驱动浏览器的开发者控制台中看到,控制器及其相关文件都已正确加载。
我看不出有什么问题?
更新
我已经尝试过传递空对象的建议:
beforeEach(inject(function($controller, $scope, $route, LoginService)
{
ctrl = $controller('LoginCtrl', {
});
}));
并设置依赖项:
beforeEach(inject(function($controller, $scope, $route, LoginService)
{
ctrl = $controller('LoginCtrl', {
$scope: $scope,
$route: $route,
LoginService: LoginService
});
}));
这两个都给我这个错误:
错误:[$injector:unpr] http://errors.angularjs.org/1.5.8/$injector/unpr?p0=%24scopeProvider%20%3C-%20%24scope
【问题讨论】:
-
哦,我知道我不是唯一一个遇到这个奇怪问题的人......我还没有弄清楚,但在我看来,生成器有问题。你在用发电机吗?
-
您的意思是样板代码生成器?如果是这样,不,从头开始。对我的服务进行了测试,也运行良好。
-
可能你忘记了这行
ctrl = $controller('LoginCtrl');中的第二个参数。您应该添加一个对象作为第二个参数,例如。ctrl = $controller('LoginCtrl', { });。这一秒模拟了 Controller 的作用域。 -
我添加了一个空对象,不同的错误。
-
它仍然很宽泛。您能否添加更多信息,例如您正在使用哪些库。欲了解更多信息,请尝试访问此link - Testing AngularJS