Ste*_*evo 14 unit-testing jasmine angularjs
我在一个有呼叫的控制器中有一个功能
var someVar = angular.element(event.target).scope().field;
Run Code Online (Sandbox Code Playgroud)
我试图通过这样做来嘲笑它
var ngElementFake = function(el) {
return {
scope: function() {
return {
toggleChildElement: true,
field: scope.field
}
}
}
}
spyOn(angular, 'element').andCallFake(ngElementFake);
Run Code Online (Sandbox Code Playgroud)
但是,当我在测试中调用该函数时,我得到了响应:
TypeError: 'undefined' is not a function (evaluating 'injector.get('$rootElement').off()')
at ../angular-mocks/angular-mocks.js:1819
Run Code Online (Sandbox Code Playgroud)
我究竟做错了什么?
编辑:注射
beforeEach(function() {
inject(function($rootScope, $controller) {
scope = $rootScope;
scope.record = recordData;
scope.model = 'Hierarchy';
ctrl = $controller("fngHierarchyChildCtrl", {
$scope: scope
});
});
});
Run Code Online (Sandbox Code Playgroud)
小智 18
我能够通过在后回调中手动清除间谍来解决这个问题.
var spy;
beforeEach(function() {
spy = spyOn(angular, 'element').andCallFake(ngElementFake);
});
afterEach(function() {
spy.andCallThrough();
});
Run Code Online (Sandbox Code Playgroud)
从 Angular 1.0.8 切换到 1.2.0 时,我在运行测试时遇到了以下错误:
TypeError: 'undefined' is not a function (evaluating 'injector.get('$rootElement').off()')
TypeError: 'undefined' is not a function (evaluating '$rootElement.on')
Run Code Online (Sandbox Code Playgroud)
解决方案是编辑 karma 配置的文件部分并将 jQuery 移至 Angular 下方:
files: [
//was here
'http://code.angularjs.org/1.2.0/angular.js',
'http://code.angularjs.org/1.2.0/angular-mocks.js',
'http://code.angularjs.org/1.2.0/angular-resource.js',
'http://code.angularjs.org/1.2.0/angular-route.js',
'http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js', //moved to here
...
]
Run Code Online (Sandbox Code Playgroud)