使用templateUrl和WITHOUT Karma对Angular指令进行单元测试

时间:2016-03-02 16:31:34

标签: javascript angularjs unit-testing jasmine

我找到了如何在不使用Karma的情况下从templateUrl加载模板的解决方案here,因此我已将此代码粘贴到我的beforeEach()并添加了检查测试:

beforeEach(inject(function ($templateCache,_$compile_, _$rootScope_, $injector, _config_, _$timeout_) {
    var directiveTemplate = null;
    var req = new XMLHttpRequest();
    req.onload = function () {
        directiveTemplate = this.responseText;
    };

    req.open("get", "js/directives/views/questionnaire-list.html", false);
    req.send();
    $templateCache.put("js/directives/views/questionnaire-list.html", directiveTemplate);

    $compile = _$compile_;
    $rootScope = _$rootScope_.$new();
    $rootScope.questionnaires = questionnaire;
    $rootScope.touchDisabled = jasmine.createSpy('touchDisabled');;
    $rootScope.onChange = jasmine.createSpy('onChange');;
    $rootScope.renderingFinished = jasmine.createSpy('renderingFinished');;

    $httpBackend = $injector.get('$httpBackend');
    config = _config_;
}));
it('compiled should not be empty', function () {

        element = angular.element('<questionnaire-list questionnaires = "questionnaires" touch-disabled = "touchDisabled()" on-change = "onChange()" rendering-finished = "renderingFinished()"></questionnaire-list>');
        var result = $compile(element)($rootScope); // Compile the directive
        $rootScope.$digest(); // Update the HTML
        var items = result.html();

        expect(items).not.toEqual("");
    });

但它等于&#34;&#34;。我究竟做错了什么?我是测试指令和angularjs本身的新手,所以我想我在使用templateCache时误解了一些东西。

指令代码:

angular.module('app.directives')
    .directive('questionnaireList', questionnaireList);

questionnaireList.$inject = ['$timeout'];

function questionnaireList($timeout) {
    return {
        restrict: 'A',
        templateUrl: 'js/directives/views/questionnaire-list.html',
        scope: {
            questionnaires: '=',
            touchDisabled: '&',
            onChange: '&',
            renderingFinished: '&'
        },
        link: link
    }

    function link(scope, element, attrs) {
        // some code goes here

    }

}

和templateUrl:

<div ng-repeat="questionnaire in questionnaires" children-same-size on-render="onContentRendered">

{{questionnaire.Title}}

<div ng-repeat="item in questionnaire.Questions" class="questions-list-item">
    <div class="question-control"><!--some text--></div>
    <div class="captions">
        <span ng-repeat="label in ::getQuestionLabels(item)">{{::label}}</span>
    </div>
</div>

提前致谢!

1 个答案:

答案 0 :(得分:0)

通过将element更改为<div questionnaire-list="" questionnaires = "questionnaires" touch-disabled = "touchDisabled()" on-change = "onChange()" rendering-finished = "renderingFinished()"></div>来解决此问题。现在items不为空且包含正确的结果。