jeudi 23 juin 2016

AngularJS Jasmine Test - Element Isolate Scope undefined

I'm trying to test a timeout, but I'm having trouble with the scope of the element. I'm new to writing JS tests.

In the it( 'should have timer defined at start' ) test, my variable logs as undefined. Why is that?

I thought isolateScope() would pull the scope of the directive in?

My test looks like this:

http://ift.tt/28PrDV3

describe( 'Testing timeout', function(){
  var scope, $timeout, element;

  beforeEach(inject( function ($rootScope, $compile, _$timeout_, $injector ){
            scope = $rootScope.$new();
            $timeout = _$timeout_;

            scope.onWarning = function(){
                scope.warned = true;
            };

            element = '<div timeout on-warning="onWarning" on-timeout="onTimeout"></div>';
            element = $compile(element)(scope);

            scope.$apply();
            scope.$digest();

  }));

  it( 'should have timer defined at start', function(){
    console.log( element.isolateScope() , scope )
    expect( element.isolateScope().timeoutService.timer ).not.toBeFalsy;
  });

  it( 'should have run warning function', function(){
    $timeout.flush( 5000 );
    expect( scope.warned ).toBe( true );
  });

});

My directive looks like this:

app.directive( 'timeout', function( timeoutService ){
  return {
    restrict: "A",
    scope: {
                onWarning: "&", // what function to fire when showing a warning
            },
            link: function( scope, elem, attr ){
                scope.timeoutService = timeoutService;
                if( !scope.onWarning ){ 
                    throw new Error( "Must provide on-warning for timeout directive." );
                }
                //console.log( scope.onWarning, scope.onTimeout );
                // register timeouts and warnings with the service
                timeoutService.onWarning = scope.onWarning; 
            }
  }
}); 

app.service( 'timeoutService', function( $timeout ){
  var _this = this;
  var timer = null;
  var time = 5000;

  this.startTimer = function(){
    timer = $timeout( function(){
      if( _this.onWarning ){
        _this.onWarning()();
      }
    }, time)
  }

  this.startTimer();

})

Maybe I'm testing incorrectly?

Aucun commentaire:

Enregistrer un commentaire