RyanP13
RyanP13

Reputation: 7743

How to unit test an AngularJS directive with shared scope of parent

I have a parent view that includes an error handling directive like so:

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

The service errors are shared with the directive and then displayed if present:

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>

I want to test that when vm.serviceErrors from the parent has data that the HTML of the service error is compiled correctly but am not sure how to set this up.

I have created a basic test so far:

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);
    });

});

Upvotes: 1

Views: 385

Answers (1)

Estus Flask
Estus Flask

Reputation: 222493

It is

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

Upvotes: 1

Related Questions