我正在尝试创建一个Angular指令来包装Snap.svg功能,但在单元测试时遇到了问题。到目前为止,我有一个指令,看起来像这样:
'use strict';
angular.module('rpApp')
.directive('rpSvgMap', function () {
return {
template: '<svg id="" width="" height=""></svg>',
restrict: 'E',
replace: true,
// Don't isolate scope because we want to attach rpMap to parent scope
link: function postLink(scope, element, attrs) {
// Set up Snap.svg wrapper
scope.rpMap = Snap('#' + attrs.id);
}
};
});我的Karma/Jasmine测试是这样的:
'use strict';
describe('Directive: rpSvgMap', function () {
// load the directive's module
beforeEach(module('rpApp'));
var element,
scope;
beforeEach(inject(function($rootScope,$compile) {
scope = $rootScope.$new();
element =
'<rp-svg-map id="anyOldID" width="800" height="400" src="../../assets/testmap.svg"></rp-svg-map>';
element = $compile(element)(scope);
scope.$digest();
}));
describe('on initialization', function() {
it('should create an SVG element with the provided dimensions and id', function() {
expect(element.attr('id')).toBe('anyOldID');
expect(element.attr('height')).toBe('400');
expect(element.attr('width')).toBe('800');
});
it('should provide a working Snap.svg drawing surface', function() {
var testCircle = scope.rpMap.circle(100,150,200);
expect(testCircle.attr(cx)).toBe(100);
});
});第一个测试通过,第二个测试失败,因为scope.rpMap总是返回"null“。
在浏览器中,这可以很好地工作--如果我将$scope附加到控制器中的窗口,Snap.svg正确地包装了rpMap,并且rpMap.circle()正确地画出了一个圆。
据我所知,测试环境正确地将snap.svg作为依赖项加载,并且我从指令中正确地读取了作用域。例如,如果我添加:
scope.hasSnap = angular.isFunction(Snap);添加到指令的链接函数,则此测试通过:
it('should tell us when Snap.svg is available', function() {
expect(scope.hasSnap).toBe(true);
});Snap()不是异步的,将beforeAll/it更改为异步模式无济于事。
你知道我哪里做错了吗?
发布于 2015-06-29 11:13:28
我找到的这个jsfiddle (对不起,不记得源代码了)包含了解决方案http://jsfiddle.net/hRy4A/2/
具体地说,我们可以将元素直接传递给Snap,如下所示:
scope.rpMap = Snap(element[0]);以这种方式创建rpMap时,将通过以下测试:
it('should provide a working Snap.svg drawing surface', function() {
var testCircle = scope.rpMap.circle(100,150,200);
expect(testCircle.attr('cx')).toBe('100');
expect(testCircle.attr('cy')).toBe('150');
expect(testCircle.attr('r')).toBe('200');
});我猜这种方法的一个潜在问题是,我不一定需要也不想在$scope中公开所有的Snap.svg方法--我认为理想情况下,图形化的东西应该都自包含在指令中。
请注意,在我最初的测试中也有一个小的拼写错误,它应该是
expect(testCircle.attr('cx')).toBe('100');https://stackoverflow.com/questions/31105460
复制相似问题