我无法开始使用Jasmine和AngularJS。我试图创建一个最小的例子,主要来自角度文档:
我在testme.js中有一个模块和一个控制器:
(function(){
"use strict";
let cont = function($scope) {
$scope.data = 99;
};
let app = angular.module('Test', []);
app.controller('Cont', cont);
}());
我有一个测试TestSpec.js
"use strict";
console.log('launching test...');
describe('Test a test', function(){
console.log('in describe...');
beforeEach(angular.module('Test'));
it('should create a number', inject(function($controller){
let scope = {};
console.log('in test...');
let ctrl = $controller('Cont', {$scope:scope}); // fails here
console.log('got controller...');
expect(scope.data).toBe(99);
console.log('test completed...');
}));
});
和SpecRunner.html
<!DOCTYPE html>
<html data-ng-app="Test">
<head>
<link rel="shortcut icon" type="image/png" href="jasmine/lib/jasmine-2.4.1/jasmine_favicon.png">
<link rel="stylesheet" href="jasmine/lib/jasmine-2.4.1/jasmine.css">
<script src="jasmine/lib/jasmine-2.4.1/jasmine.js"></script>
<script src="jasmine/lib/jasmine-2.4.1/jasmine-html.js"></script>
<script src="jasmine/lib/jasmine-2.4.1/boot.js"></script>
<script src="scripts/angular.js"></script>
<script src="scripts/angular-mocks.js"></script>
<script src="scripts/testme.js"></script>
<script src="test/TestSpec.js"></script>
</head>
<body data-ng-controller="Cont">
<h1>Value is {{data}}</h1>
</body>
</html>
好像它启动了,我收到了消息
启动测试...... 在描述... 在测试...
但它在TestSpec.js中尝试执行我标记为//失败的行失败。这告诉我,我没有设法检索控制器。毋庸置疑,我不明白为什么(关于这个主题有很多问题,但就我所知,它们似乎都不适用于此。)
谢谢! 托比
答案 0 :(得分:2)
答案 1 :(得分:1)
您应该创建一个新范围作为$rootScope
的子级。在测试中用以下替换行来创建范围:
beforeEach(angular.mock.module('Test'));
it('should create a number', inject(function($controller, $rootScope){
let scope = $rootScope.$new();
console.log('in test...');
let ctrl = $controller('Cont', {$scope:scope});
console.log('got controller...');
expect(scope.data).toBe(99);
console.log('test completed...');
}));
此外,您不应使用angular.module
,而应使用angular.mock.module
来引用模块
答案 2 :(得分:0)
你没有注入你的控制器依赖关系,你的结构有点偏。您不需要分配块级变量。
(function(){
"use strict";
angular.module('Test', [])
.controller('Cont', cont);
Cont.$inject = ['$scope'];
function cont($scope) {
$scope.data = 99;
};
}());