我创建了伪指令,如果图像的src不可用,则该伪指令将创建图像的链接,如下所示:
var app = angular.module('myApp', []);
app.directive('defaultImage', function() {
return {
restrict: 'EA',
link: function(scope, element, attrs) {
var url = 'http://placehold.it/' + element.attr('default-image');
element.bind('error', function() {
element.addClass('default-image');
element.attr('src', url);
})
}
};
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="myApp">
<img ng-src="/logo.jpg" default-image="103x89" alt="Logo!" />
</div>
它可以按预期工作,但是我想要为该指令创建一个测试单元,我尝试了很多方法,但是我无法使测试正常工作,测试代码如下:
'use strict';
describe('Directive: defaultImage', function () {
var element, compile, scope;
// load the directive's module
beforeEach(module('myApp'));
beforeEach(inject(function ($rootScope, $compile) {
scope = $rootScope;
compile = $compile;
}));
function compileImage(markup, scope){
var el = compile(markup)(scope);
scope.$digest();
return el;
}
it('should make image with default image src link', inject(function () {
var image = compileImage('<img ng-src="/logo.jpg" default-image="200x48" alt="Default Image!" class="img"/>', scope);
expect(image.attr('src')).toEqual('http://placehold.it/200x48');
}));
});
感谢您的任何建议,
您将绑定到指令中的错误事件
element.bind('error', function() {
element.addClass('default-image');
element.attr('src', url);
})
但是,上面的代码永远不会在您的测试中触发,因此它将始终失败。只需在测试中手动触发错误即可解决该问题。
it('should make image with default image src link', inject(function() {
var image = compileImage('<img ng-src="/logo.jpg" default-image="200x48" alt="Default Image!" class="img"/>', scope);
image.error(); // Trigger the error manually
expect(image.attr('src')).toEqual('http://placehold.it/200x48');
}));
您可以从任何浏览器调试业力测试
http://localhost:9876/debug.html
(默认业力配置,可能有所不同)使用这种方法,您可以更轻松地缩小测试中的任何问题。
干杯
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句