mercredi 24 décembre 2014

angular jasmine: 'undefined' is not an object - broadcast within timeout - error

I have a function like this:



$scope.doIt = function( x, y )
{
$timeout( function ()
{
$rootScope.$broadcast( 'xxx',
{
message: xxx,
status: xxx
} );
} );
}


This function works fine so far. But while writing a test I had some trouble.



describe( 'test doIt function...', function ()
{
var $rootScope, $timeout;

beforeEach( inject( function ( _$rootScope_, _$timeout_ )
{
$rootScope = _$rootScope_;
$timeout = _$timeout_;
spyOn( $rootScope, '$broadcast' );
spyOn( scope, 'doIt' ).and.callThrough();
} ) );

it( 'test broadcast will be called', inject( function ()
{
var testObj = {
message: 'test1',
status: 'test2'
};

scope.doIt( 'test1', 'test2' );

expect( $rootScope.$broadcast ).not.toHaveBeenCalledWith( 'xxx', testObj );

$timeout.flush();

expect( $rootScope.$broadcast ).toHaveBeenCalledWith( 'xxx', testObj );

} ) );
}
);


This will end up in the following error:



TypeError: 'undefined' is not an object (evaluating '$rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, $location.$$state, oldState).defaultPrevented')



Why? What I am doing wrong? Without $timeout in function and test it works fine.


Thanks in advance for your help.


:)


Aucun commentaire:

Enregistrer un commentaire