3

ディレクティブ内に d3 視覚化があります。これに関する問題は、要素 [0] を d3 ビジュアライゼーションのコンテナーに設定するなど、他の多くのビジュアライゼーションで再利用できる多くのボイラープレート コードがあることです。そこで、ディレクティブで行われていたすべての作業を実行するサービスを作成し、DRY を維持することにしました。私は現時点でテストに行き詰まっており、これが私が助けを得たいと思っていたところです。私のコードは次のとおりです

指令


angular.module('app')
  .directive('barchart', function (Barchartservice) {
    return {
      restrict: 'E',
      link: function postLink(scope, element, attrs) {

        scope.$on('drawCharts',function(ev,attrs){
          draw();
        });

        function draw(){
          if(!scope.dataset) return;

          var svg = Barchartservice.setContainer(svg, element);
          .
          .
          .
          .

        }
      }
    };
  });


サービス


angular.module('app')
  .service('Barchartservice', function Barchartservice() {
    var margin = {top: 50, right: 20, bottom: 50, left: 40},
              container,
              width = (1120 || container.width() - 20) - margin.left - margin.right,
              height = 400 - margin.top - margin.bottom;
    return{
        setContainer: function(svg, element){
            container  = angular.element(element);
            svg = d3.select(element[0]).append('svg')
                    .attr('width', width + margin.left + margin.right)
                    .attr('height', height + margin.top + margin.bottom)
                    .append('g')
                    .attr('transform', 'translate(' + margin.left + ',' + margin.top + ')');
        return svg;
        }
    }
  });

テスト


'use strict';

describe('Service: Barchartservice', function () {

  // load the service's module
  beforeEach(module('clientApp'));

  // instantiate service
  var Barchartservice;
  beforeEach(inject(function (_Barchartservice_) {
    Barchartservice = _Barchartservice_;
  }));

  it('should insert an svg element into the barchart directive', function () {
    var svg = undefined;
    var element = [];
    element[0] = '<barchart></barchart>';
    expect(Barchartservice.setContainer()).toEqual('<barchart><svg></svg></barchart>');
  });

});

エラー


PhantomJS 1.9.2 (Mac OS X) Service: Barchartservice should do something FAILED
    TypeError: 'undefined' is not an object (evaluating 'element[0]')

どんな助けでも大歓迎です。ありがとう!

4

1 に答える 1

1

要素をコンパイルする必要があります。AngularJS をテストするときは、ディレクティブのコンパイルと dom ツリーへのリンクを制御する必要があります。これも完了したら、scope.$apply() を呼び出す必要もあります。

そのため、最初に $compile サービスと $rootScope サービスを beforeEach DI ブロックに挿入する必要があります。

テスト用にクリーンなスコープを参照できるように、beforeEach にもscope = $rootScopeを設定します。

var element = $compile('<barchart></barchart>')(scope);
scope.$apply();
expect(Barchartservice.setContainer()).toEqual('<barchart><svg></svg></barchart>');

これで先に進むことができますが、テストに完全には合格しない可能性があります。実際に setContainer 関数を実行するには、 drawCharts イベントもブロードキャストする必要があるようです。したがって、これも問題になる可能性があります。

于 2013-11-29T23:30:16.253 に答える