【问题标题】:How to unit test an AngularJS directive with shared scope of parent如何对具有父共享范围的 AngularJS 指令进行单元测试
【发布时间】:2016-05-27 03:14:57
【问题描述】:

我有一个包含错误处理指令的父视图,如下所示:

<service-error the-errors="vm.serviceErrors"></service-error>

服务错误与指令共享,如果存在则显示:

class ServiceError implements ng.IDirective{

    public restrict: string;
    public template: string;
    public controller: string;
    public controllerAs: string;
    public bindToController: boolean;
    public scope: Object;

    constructor(...deps: Array<any>) {
        this.restrict = 'E';
        this.template = require('./service.error.directive.html');
        this.controller = 'ServiceErrorController';
        this.controllerAs = 'vm';
        this.bindToController = true;
        this.scope = {
            theErrors: '='
        };
    }

    static factory(...deps: Array<any>) {
        return new ServiceError(...deps);
    }

}

// Dependency Injection
ServiceError.factory.$inject = [];

export { ServiceError };

<ul class="list-unstyled service-error">
    <li class="bg-danger" ng-repeat="error in vm.theErrors track by $index">{{error.message}}</li>
</ul>

我想测试一下,当来自父级的vm.serviceErrors 有数据表明服务错误的 HTML 已正确编译但不知道如何设置时。

到目前为止,我已经创建了一个基本测试:

describe('Directive: Service Error', function() {

    var element,
        scope,
        template;

    beforeEach(inject(function(_$rootScope_, $compile) {
        element = angular.element('<service-error the-errors="vm.serviceErrors"></service-error>');
        scope = _$rootScope_.$new();
        template = $compile(element)(scope);
        scope.$digest();
    }));

    it('should compile error list', function(){
        var el = element.find('.service-error');
        assert.isDefined(el);
    });

});

【问题讨论】:

    标签: angularjs unit-testing angularjs-directive karma-runner


    【解决方案1】:

    是的

        element = angular.element('<service-error the-errors="serviceErrors"></service-error>');
        scope = _$rootScope_.$new();
        scope.serviceErrors = ...;
        template = $compile(element)(scope);
        scope.$digest();
    

    【讨论】:

      猜你喜欢
      • 2013-06-26
      • 1970-01-01
      • 2013-10-07
      • 1970-01-01
      • 1970-01-01
      • 2017-08-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多