首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >单元测试AngularJS指令包装Snap.svg

单元测试AngularJS指令包装Snap.svg
EN

Stack Overflow用户
提问于 2015-06-29 06:37:54
回答 1查看 472关注 0票数 2

我正在尝试创建一个Angular指令来包装Snap.svg功能,但在单元测试时遇到了问题。到目前为止,我有一个指令,看起来像这样:

代码语言:javascript
复制
'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测试是这样的:

代码语言:javascript
复制
'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作为依赖项加载,并且我从指令中正确地读取了作用域。例如,如果我添加:

代码语言:javascript
复制
scope.hasSnap = angular.isFunction(Snap);

添加到指令的链接函数,则此测试通过:

代码语言:javascript
复制
it('should tell us when Snap.svg is available', function() {
      expect(scope.hasSnap).toBe(true);
    });

Snap()不是异步的,将beforeAll/it更改为异步模式无济于事。

你知道我哪里做错了吗?

EN

回答 1

Stack Overflow用户

发布于 2015-06-29 11:13:28

我找到的这个jsfiddle (对不起,不记得源代码了)包含了解决方案http://jsfiddle.net/hRy4A/2/

具体地说,我们可以将元素直接传递给Snap,如下所示:

代码语言:javascript
复制
scope.rpMap = Snap(element[0]);

以这种方式创建rpMap时,将通过以下测试:

代码语言:javascript
复制
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方法--我认为理想情况下,图形化的东西应该都自包含在指令中。

请注意,在我最初的测试中也有一个小的拼写错误,它应该是

代码语言:javascript
复制
expect(testCircle.attr('cx')).toBe('100');
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31105460

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档