我正在尝试对如下所示的简单指令进行单元测试:
angular.module('blog').directive('imageOnLoad', function() {
return {
restrict: 'A',
link: function(scope, element, attrs, fn) {
element.bind('load', function() {
scope.$emit('resizeContent');
});
}
};
});
我可以看到我需要在这里测试的两件事是它绑定(bind)到图像加载事件,该事件又会发出 resizeContent 事件。
我的单元测试中有以下内容 - 目前只是测试事件绑定(bind):
describe('imageOnLoad', function() {
beforeEach(module('blog'));
var scope,compile, element;
beforeEach(inject(function($rootScope,$compile) {
scope = $rootScope.$new();
compile = $compile;
var elementString = '<img ng-src="123.jpg" image-on-load />';
element = $compile(elementString)(scope);
}));
it('should bind to the load event of the image', function() {
spyOn(element, 'bind').andCallThrough();
expect(element.bind).toHaveBeenCalled();
});
});
我的问题:加载事件似乎永远不会触发。我的第一个猜测是,这是因为 123.jpg 图像不存在 - 如果是这样,我的问题是如何模拟它,这样我就不必在其中携带物理图像文件。
最佳答案
成功了,也是我设置顺序的问题。它通过调用隐式测试图像加载事件绑定(bind)。这是工作代码:
describe('imageOnLoad', function() {
beforeEach(module('blog'));
var scope,compile, element;
beforeEach(inject(function($rootScope,$compile) {
scope = $rootScope.$new();
compile = $compile;
element = angular.element('<img ng-src="123.jpg" image-on-load />');
$compile(element)(scope);
}));
it('should emit the resizeContent signal when the load event occurs', function() {
spyOn(scope, '$emit');
element.trigger('load');
expect(scope.$emit).toHaveBeenCalledWith('resizeContent');
});
});
关于javascript - 如何在 AngularJS/Jasmine 单元测试中模拟图像加载事件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27621168/