div*_*iv5 5 javascript unit-testing jasmine angularjs
这里有几个指令和单元测试.
这是第一个指令:
directive('myTestDirective', function() {
return {
link: function(scope, element, attrs) {
element.on("click", function(e) {
scope.clicked = true;
console.log("clicked");
}
}
});
Run Code Online (Sandbox Code Playgroud)
单元测试:
describe('my test directive', function() {
beforeEach(function() {
.....
inject($compile, $rootScope) {
scope = $rootScope.$new();
html = '<div my-test-directive></div>';
elem = angular.element(html);
compiled = $compile(elem);
compiled(scope);
scope.$digest();
}
});
it('should set clicked to true when click() is called', function() {
elem[0].click();
expect(scope.clicked).toBe(true);
});
});
Run Code Online (Sandbox Code Playgroud)
运行上述单元测试时,测试通过并clicked记录到控制台.
但是,请考虑restrict: E添加以下指令:
directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
element.on("click", function(e) {
scope.clicked = true;
console.log("clicked");
}
}
});
Run Code Online (Sandbox Code Playgroud)
单元测试:
describe('my directive', function() {
beforeEach(function() {
.....
inject($compile, $rootScope) {
scope = $rootScope.$new();
html = '<my-directive></my-directive>';
elem = angular.element(html);
compiled = $compile(elem);
compiled(scope);
scope.$digest();
}
});
it('should set clicked to true when click() is called', function() {
elem[0].click();
expect(scope.clicked).toBe(true);
});
});
Run Code Online (Sandbox Code Playgroud)
此测试失败.clicked未记录到控制台.从调试中我可以看到绑定click()指令绑定的函数没有被执行.
如何继续使用restrict : 'E',同时仍保留在单元测试中模拟点击的功能?
更新:感谢Michal的傻瓜,我有它的工作.
我将inject()函数更改为:
inject(function($compile, $rootScope, $document) {
scope = $rootScope.$new();
html = '<my-test-directive-element></my-test-directive-element>';
elem = angular.element(html);
$compile(elem)(scope);
scope.$digest();
});
Run Code Online (Sandbox Code Playgroud)
在此之后,单击使用restrict属性和限制元素工作.
Plukr在这里:http://plnkr.co/edit/fgcKrYUEyCJAyqc4jj7P
使用 jqLite on('click') 并不是很 Angular 风格,我不认为它会被 Angular 摘要循环处理(因此,您在该回调中添加到范围的任何内容都不会在 DOM 中呈现,除非您手动进行)。您应该更喜欢使用内置的 ng-click 指令,因此 html 代码变为:
<my-directive ng-click="onClick()"></my-directive>
Run Code Online (Sandbox Code Playgroud)
和你的指令:
directive('myDirective', function() {
return {
restrict: 'E',
link: function(scope, element, attrs) {
scope.onClick = function() {
scope.clicked = true;
console.log("clicked");
}
}
}
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3745 次 |
| 最近记录: |