2016-03-18 21 views
0

我想寫sigma角度指令的單元測試,但我得到這個錯誤。 the string "Container not found." was thrown, throw an Error :) 的源代碼字符串「找不到容器」。拋出一個錯誤:)在摩卡西格瑪角度指令測試期間

angular 
    .module('test') 
    .directive('sigmagraph', directive); 

function directive() { 

     var divId = 'sigma-container-' + Math.floor(Math.random() * 999999999999); 
     return{ 
      restrict: 'E', 
      transclude: true, 
      template: '<div id="' + divId + '" style="width: 100%;height: 100%;" class="sigmaContainer">' + 
         '</div>', 
      scope: { 
       graph: '=', 
       isVisible: '=' 
      }, 
      link: function (scope, element, attrs, ctrl) { 
       // Create a sigma instance. 
       var sigmaInstance = new sigma({ 
        settings: _newSigmaSettings, 
        renderer: { 
         container: divId, 
         type: 'canvas' 
        } 
       }); 
       //other code.. 
      } 
     } 
    }  

測試代碼

describe('sigmagraph', function() { 
var scope,element; 
beforeEach(function() { 
    module('ui.router'); 
    module('tresata.orion'); 
    module('core'); 


    inject(function ($compile, $rootScope, $templateCache) { 
     // $templateCache.put('<div class="sigmaContainer"></div>'); // also tried this but its not working 
     scope = $rootScope.$new(); 
     element = angular.element('<sigmagraph graph="graph" is-visible="view.graphView">'); 
     scope.graph = mockGraphData; 
     $compile(element)(scope); 
     $rootScope.$digest(); 
    }); 
}); 

it('should apply template', function() { 
    expect(element.html()).to.not.be.empty; 
}); 

我也試圖解決使用$ templateCache這個問題,但它仍然無法正常工作。我是初學者,所以可能是我錯過了一些東西。請幫我解決這個問題。

回答

0

我已經解決了與您的問題相同的問題。

因爲你的指令有一個鏈接函數,它將在編譯後執行,並且此時在DOM上沒有附加任何元素。

所以如果你使用的$compile服務動態編譯指令,you'b更好地追加您的指令元素之前編譯它。修改下面的代碼可能會對您有所幫助:

inject(function ($compile, $rootScope, $templateCache) { 
    // $templateCache.put('<div class="sigmaContainer"></div>'); // also tried this but its not working 
    scope = $rootScope.$new(); 
    scope.graph = mockGraphData; 
    element = angular.element('<sigmagraph graph="graph" is-visible="view.graphView">'); 
    angular.element('body').append(element); 
    $compile(element)(scope); 
    $rootScope.$digest(); 
}); 
+0

非常感謝。它幫助我很多 – Jaydipsinh

相關問題