【发布时间】:2015-02-25 13:10:47
【问题描述】:
我第一次尝试为 Angular 应用程序编写单元测试。目前我在运行测试时遇到了一些问题。运行应用程序通常工作正常,它不会给出任何错误。但是,当使用 Karma 和 Jasmine 运行测试时,出现以下错误:
TypeError: 'undefined' is not a function (evaluating '$scope.addActiveClassToMenuButton('menuButtonHome')')
我正在使用 ui.router 模块。不确定这是否重要。
父控制器
父控制器包含以下方法:
angular.module('testApp')
.controller('ParentCtrl', function ($scope, $resource) {
$scope.addActiveClassToMenuButton = function(buttonId) {
//Some code
}
}
儿童控制器
子控制器像这样调用父母方法:
angular.module('testApp')
.controller('ChildCtrl', function ($scope, $resource) {
$scope.addActiveClassToMenuButton('menuButtonHome');
}
子控制器测试文件
失败的测试文件:
describe('Child controller tests. ', function () {
beforeEach(module('testApp'));
var ChildCtrl, scope;
beforeEach(inject(function ($controller, $rootScope) {
scope = $rootScope.$new();
ChildCtrl = $controller('ChildCtrl', {
$scope: scope
});
}));
it('simple false test', function () {
expect(false).toBe(false);
});
});
即使我还没有在测试中使用范围,所有测试都失败了,因为代码找不到父方法。
解决方案
将测试文件更改为此有效:
describe('Child controller tests. ', function () {
beforeEach(module('testApp'));
var controller, scope, parentScope, childScope;
beforeEach(inject(function ($controller, $rootScope, $compile) {
scope = $rootScope.$new();
var el = angular.element('<div ng-controller="ParentCtrl"><div ng-controller="ChildCtrl"></div></div>');
$compile(el)(scope);
parentScope = el.scope();
childScope = el.children().scope();
}));
it('simple false test', function () {
expect(false).toBe(false);
});
});
【问题讨论】:
标签: javascript angularjs unit-testing jasmine