我真的很难在angularjs指令上运行业力单元测试 . 这是我的设置:
var scope, ele;
var template = '<div data-my-directive data="data" config="config"></div>';
beforeEach(function () {
// Load directive's module
module('dashboard');
module('templates-dev');
// Load mock services/data (overriding real implementation)
module(function($provide) {
$provide.value("MockWidgetData", new MockWidgetData());
});
// Construct services/data to be available
// inside each testing block.
inject(function($rootScope, $compile, MockWidgetData) {
// Create a fresh scope
scope = $rootScope.$new();
ele = angular.element(template);
// Fill that scope with mock data
scope.config = MockWidgetData.config;
scope.data = MockWidgetData.data;
// Compile the element and attach our scope
$compile(ele)(scope);
// Digest the scope to trigger a scope update
// and attach our directive's link function
scope.$digest();
});
});
我的指令将'data'和'config'对象传递给它的子对象,这恰好是其他指令 . 该指令本身使用 templateUrl
,这就是为什么我提供 module(templates-dev)
:html2js预编译,角度模块化, $templateCache
'd version of my templates. Here' s我的指令 templateUrl
的样本:
<div id="container">
<button id="my-btn" ng-click="doSomething('parameter')"></button>
<div other-dir data="data" config="config"></div>
</div>
以下是我的指令示例:
angular.module('dashboard').directive('myDirective', function() {
return {
restrict: 'A',
templateUrl: 'my-dir-template.html',
scope: { //
data: '=',
config: '='
},
replace: true,
link: function(scope, element, attrs) {
scope.someFunc() = { ... },
scope.someFunc1() = { ... },
});
Problem:
-
在$ compile(ele)(范围)之后,元素的.log()显示整个DOM,包括各种angular.js指令和其他奇怪的信息 . 我希望看到我的指令的测试模板与上面的templateUrl一起被捣碎 .
-
作用域的.log()显示完整的数据和配置对象及其预期值 . 它还显示了我的指令's link function, as one would expect. However, inside my test blocks, it'中可用的函数,就好像范围对象被清空一样......我无法访问任何指令的函数(它们都返回undefined) .
-
我能够通过
ele.find("#my-btn").eq(0)
捕获我的指令html的一些元素,但没有一个正常的函数可以工作(.click()等) .
我究竟做错了什么?编译过程有问题吗?我构建测试错了吗?我应该尝试删除链接功能并将其替换为控制器吗?我的范围只是没有排队,而且我已经在这两天失败了......有点烦人 .
经过仔细检查......看起来我可以在 $compile(ele)(scope)
之前 scope.$digest()
,它会正确地将"data"和"config"对象传播到子范围 . 但是,我的范围失去了对我的指令链接中定义的函数的访问权限 .
1 回答
您应该在
$compile(ele)(scope)
之后调用scope.$digest()
. 摘要是进行指令编译所必需的 . 您的指令具有独立的范围,'s why you can' t访问它的功能 . 为了得到它们你应该试试这个:var elScope = element.isolateScope();
这里有你的elScope.someFunc();
检查单元测试指令的这个示例:
http://best-web-creation.com/articles/view/id/angular-js-unit-test-directive?lang=en