the string "Container not found." was thrown, throw an Error :) during mocha sigma angular directive testing

the string "Container not found." was thrown, throw an Error :) during mocha sigma angular directive testing

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

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

因为你的指令有一个link函数,编译后会执行,而此时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();
});