jeudi 29 octobre 2015

Access scope variable in unit test

I'm trying to access the scope.loading variable in my unit test. The idea is to test that the $on listener fires correctly.

scope.loading is defaulted to false in the link function of my directive. It should be updated to true when the $on function receives the 'loadingPosts' $broadcast from $rootScope.

However, the test case always fails saying the scope.loading is undefined. Where am I going wrong?

Here's my test case:

'use strict';

describe('ngPress', function()
{
    beforeEach(module('ngPress'));

    describe('ngpLoader directive', function()
    {
        it('loading event fires', function()
        {
            inject(function($compile, $rootScope)
            {
                var scope = $rootScope.$new();

                var element = $compile('<ngp-loader type=\"posts\"></ngp-loader>')(scope);

                $rootScope.$broadcast( 'loadingPosts' );

                expect( scope.loading ).toEqual( true );
            });
        });
    });
});

And here's the directive:

(function ()
{
    angular.module('ngPress').directive('ngpLoader',
        [function ()
        {
            var link = function(scope, element, attrs)
            {
                scope.loading = false;

                scope.$on( 'loading'+scope.type.capitalizeFirstLetter(), function()
                {
                    scope.loading = true;
                });

                scope.$on( scope.type+'Loaded', function()
                {
                    scope.loading = false;
                });

                scope.$on( scope.type+'LoadFailed', function()
                {
                    scope.loading = false;
                });
            };

            return {
                link: link,
                restrict: 'E',
                replace: true,
                template: '<div class="loader" ng-show="loading"></div>',
                scope: {
                    type: '@'
                }
            };
        }]);
}());

Aucun commentaire:

Enregistrer un commentaire