jasmine angularjs 测试 - 参数“PhoneListCtrl”不是函数,未定义
-
21-12-2019 - |
题
运行 angularjs + Jasmine + Karma 测试时,出现以下错误:
我的测试脚本是:
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
it('should create "phones" model with 3 phones', inject(function($controller) {
var scope = {},
ctrl = $controller('PhoneListCtrl', { $scope: scope });
expect(scope.phones.length).toBe(3);
}));
});
});
这段代码只是 AngularJS 官方教程的副本:http://code.angularjs.org/1.2.0-rc.3/docs/tutorial/step_02
这是我的 karma.conf.js 文件的一部分:
// list of files / patterns to load in the browser
files: [
'js/bower_components/angular/angular.js',
'js/bower_components/angular/ngular-mocks.js',
'js/app/controllers.js',
'test/unit/*.js'
],
错误是 电话列表控件 没有定义,但我相信它是在上面的代码中定义和加载的。您认为问题出在哪里?谢谢!
解决方案
您的单元测试中缺少模块初始化部分。你应该打电话 module('phonecatApp')
在你第一次打电话之前 inject()
. 。在这种情况下,您的单元测试代码应如下所示:
describe('PhoneCat controllers', function() {
describe('PhoneListCtrl', function(){
beforeEach(function() {
module('phonecatApp'); // <= initialize module that should be tested
});
it('should create "phones" model with 3 phones', inject(function($controller) {
var scope = {},
ctrl = $controller('PhoneListCtrl', { $scope: scope });
expect(scope.phones.length).toBe(3);
}));
});
});
在哪里 phonecatApp
是您定义的模块的名称 PhoneListCtrl
控制器。
另外,您使用的教程已过时,它适用于不稳定版本的 Angular (1.2.0-rc.3)。以下是针对最新版本 Angular 的同一教程的更新版本: http://docs.angularjs.org/tutorial/step_02
其他提示
这适用于我
describe('addCatControllerTest', function() {
describe('addCatController', function(){
beforeEach(function() {
module('app');
});
beforeEach(inject(function($controller, $rootScope){
$scope = $rootScope.$new();
}));
it('Add Cat Controller test', inject(function($controller) {
var scope = {},
ctrl = $controller('addCatController', { $scope: scope });
expect(scope.title).toBe('Add Cat');
}));
});
});
. 不隶属于 StackOverflow