【问题标题】:the string "Container not found." was thrown, throw an Error :) during mocha sigma angular directive testing字符串“找不到容器”。被抛出,在 mocha sigma 角度指令测试期间抛出错误 :)
【发布时间】:2016-03-18 09:52:47
【问题描述】:

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

【问题讨论】:

    标签: angularjs mocha.js chai sigma.js linkurious


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2015-09-01
      • 2021-09-28
      • 1970-01-01
      • 2012-11-21
      • 1970-01-01
      • 2015-06-27
      • 1970-01-01
      • 2013-02-04
      • 1970-01-01
      相关资源
      最近更新 更多