0

我正在尝试为 sigma angular 指令编写单元测试,但我收到了这个错误。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 解决这个问题,但它仍然无法正常工作。我是测试的初学者,所以可能我错过了一些东西。请帮我解决这个问题。

4

1 回答 1

0

我已经解决了一个和你一样的问题。

因为你的指令有一个链接函数,编译后会执行,此时DOM上没有附加任何元素。

因此,如果您使用该$compile服务动态编译指令,则最好在编译之前附加指令元素。修改如下代码可能会对您有所帮助:

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();
});
于 2016-11-03T07:06:25.680 回答