jeudi 30 juillet 2015

How to test angular directive scope

I am running to an issue for the unit test

I have something like

describe('test controller', function () {
    var =$compile, scope, rootScope;

    beforeEach(module('myApp'));
    beforeEach(inject(function (_$compile_, _$rootScope_) {
       $compile   = _$compile_;
        rootScope   = _$rootScope_;
        scope        = _$rootScope_.$new();
    }));

    describe('test', function() {
        beforeEach(function () {
            scope.toys = ['toy1', 'toy2'];            
        });
        it('should test directive' , function() {
            var element = $compile('<button type="button"  show-item>See all</button>')($rootScope);
            element.triggerHandler('click');
            $rootScope.$digest();
        });
    });
});

html

   <button type="button"  show-item>See all</button>

Directive

angular.module('myApp').directive('showItem', 
function() {
    return {
        restrict: 'A',
        scope: false,
        link: function(scope, elem, attrs) {                
            elem.bind('click', function() {
                var l = scope.toys.length;
                //other codes
            });
     }
});

I am getting undefined' is not an object (evaluating 'scope.toys.length') when I run the unit test.

I am not sure what went wrong as I already specify scope.toys inside beforeEach function. Can anyone help me about it? Thanks a lot!

Aucun commentaire:

Enregistrer un commentaire