Angular测试不执行指令代码
angular test not executing directive code
我在测试angular指令时遇到了一些麻烦。这就是我所经历的。我已经安排好了卡玛来做测试。似乎指令中的链接代码(控制台日志"启动计算"的部分)从未真正触发。我不确定我做错了什么。测试的工作方式与我所期望的一样——除了当我深入到imageNode时。风格——里面什么都没有。没有为图像分配样式。为什么指令代码没有被触发?什么好主意吗?
这是我的模块代码
(function() {
'use strict';
// sets narrower side of image to width of parent div
// used in sjwUserImage
angular.module('sjw.util', [])
.directive('imgFit', function() {
return {
restrict: 'A',
link: function(scope, element, attr) {
element.bind('load', function(e) {
console.log('kicking off calculations...');
console.log(element);
var parentWidth = element.parent().width();
if (this.naturalHeight > this.naturalWidth) {
// not horizontal or square
this.width = parentWidth;
}
else {
this.height = parentWidth;
}
});
}
};
});
})();
这是我的测试代码
describe('imgFit directive', function() {
var compile;
var scope;
var directiveElem;
console.log('loading sjw.util module...');
beforeEach(function(done) {
module('sjw.util', function() {
console.log('completed loading module.');
});
inject(function($compile, $rootScope) {
angular.module('sjw.util');
compile = $compile;
scope = $rootScope.$new();
directiveElem = getCompiledElement();
done();
});
});
function getCompiledElement() {
var myApp = angular.module('sjw.util');
var elem = angular.element(
'<div style="height:35px;width:35px">' +
'<img ' +
'ng-src="http://random_image_url" img-fit>' +
'</div>' +
'<div style="height:35px;width:35px">' +
'<img ' +
'ng-src="http://random_image_url" img-fit>' +
'</div>');
var compiledDirective = compile(elem)(scope);
scope.$digest();
return compiledDirective;
}
it('should assign width to parent width when image is square', function() {
var squareImageParent = directiveElem[0];
console.log(directiveElem);
expect(squareImageParent).not.toBe(null);
var imageNode = squareImageParent.childNodes[0];
expect(imageNode).toBeDefined();
console.log(imageNode);
console.log(imageNode.style);
//expect(imageNode.style.height == '35px').toBe(true);
});
});
我已经驱除了这个恶魔。我的问题是指令本身。在我使用的无头浏览器中,我的图像没有完成加载。在imgFit中的load事件。林克永远不会开火。这显然是个问题。这就是为什么插入超时(在上面的评论中)是有帮助的。它允许图像完成加载。难看的黑客,但我似乎不知道幻影什么时候会载入图像。
beforeEach(function(done) {
module('sjw.util');
inject(function($compile, $rootScope) {
compile = $compile;
scope = $rootScope.$new();
directiveElem = getCompiledElement();
// wait for the images to finish loading.
setTimeout(done, 2000);
});
});
相关文章:
- 这段jquery代码在angular指令中不起作用
- 指令中的跟踪代码脚本
- 验证指令代码在ng重复中的每个项目上执行
- 用于按键重定向的 AngularJS 代码应该是服务或指令
- 角度:不呈现模板的指令代码
- 如何将 javascript 或 jquery 代码添加到 angularjs 指令中
- 角度指令限制 E 中断代码
- Angular.js 和 Fabric.js:一旦代码移动到 Angular 指令,Fabric canvas 就会改变
- 范围更改不会;t执行指令中的代码
- Angular JS-需要与页面上的所有指令进行通信,这些指令来自只运行一次的服务中的代码
- 指令's的代码在我得到数据之前就启动了
- Angularjs将代码转换为指令或ng重复
- 写angular指令时,我应该把公共代码放在哪里?
- 在ng-src之后运行指令代码
- 如何在不发送HTML代码的情况下共享AngularJS指令
- 如何在angularJS中重构指令代码
- 在控制器前执行指令代码
- Angular测试不执行指令代码
- 在angularjs 1.2.29中,自定义指令标签不会触发指令代码
- 如何在Angular中更改状态时停止指令代码的运行