我在一个单独的文件中有一个角度模块 的 userModule.js
'use strict';
angular.module('users', ['ngRoute','angular-growl','textAngular','ngMaterial','ngMessages','ngImgCrop','ngFileUpload'])
.run(function ($rootScope, $location, $http) {
$http.get('/token')
.success(function (user, status) {
if (user) {
$rootScope.user = user;
}
});
})
我在一个单独的另一个文件中使用该模块的控制器:
userController.js
'use strict';
var usersApp = angular.module('users');
usersApp.controller('usersControllerMain', ['$scope', '$http', '$routeParams','$location', 'growl','$rootScope','$mdDialog','API',
function($scope, $http, $routeParams, $location,growl,$rootScope,$mdDialog,API) {
$scope.action = "none";
$scope.password = '',
$scope.grade = function() {
var size = $scope.password.length;
if (size > 8) {
$scope.strength = 'strong';
} else if (size > 3) {
$scope.strength = 'medium';
} else {
$scope.strength = 'weak';
}
};
我的控制器中定义了一些用于其他用途的依赖项。
现在我需要测试这个控制器。所以我写了一个我直接在浏览器中运行的spec文件。我不想使用像业力这样的测试跑步者: 的 jasmine.html
<html>
<head>
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.8/angular.js"></script>
<script type="text/javascript" src="https://code.angularjs.org/1.4.8/angular-mocks.js"></script>
<script type="text/javascript">
describe('userControllerMain testing', function(){
beforeEach(angular.mock.module('users'));
var $controller;
beforeEach(angular.mock.inject(function(_$controller_){
$controller = _$controller_;
}));
describe('$scope.grade', function() {
it('sets the strength to "strong" if the password length is >8 chars', function() {
var $scope = {};
var controller = $controller('usersControllerMain', { $scope: $scope });
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
});
</script>
</head>
<body>
</body>
</html>
我从this question获取了这个例子。 但是当我在浏览器中运行我的jasmine.html时,它会抛出一个注入模块错误,如下所示: angular docs 。我在这做错什么.. ??
答案 0 :(得分:0)
您在此处遵循的方法存在严重错误。您应该在beforeEach
块而不是it
块中模拟控制器。
这就是你的测试文件应该是这样的:
describe('userControllerMain testing', function(){
beforeEach(module('users'));
beforeEach(inject(function($controller, $rootScope) {
$scope = $rootScope.$new();
usersControllerMain = $controller('usersControllerMain', {
$scope: $scope
});
}));
describe('$scope.grade', function() {
it('sets the strength to "strong" if the password length is >8 chars', function() {
$scope.password = 'longerthaneightchars';
$scope.grade();
expect($scope.strength).toEqual('strong');
});
});
});
希望这有帮助。