angular jasmine:'undefined'不是对象 - 在超时内广播 - 错误

And*_* D. 10 javascript testing jasmine angularjs karma-runner

我有这样的功能:

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

到目前为止,此功能正常.但在写测试时我遇到了一些麻烦.

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

        } ) );
      }
    );
Run Code Online (Sandbox Code Playgroud)

这将最终出现以下错误:

TypeError:'undefined'不是对象(评估'$ rootScope.$ broadcast('$ locationChangeStart',newUrl,oldUrl,$ location.$$ state,oldState).defaultPrevented')

为什么?我做错了什么?没有$ timeout功能和测试它工作正常.

在此先感谢您的帮助.

:)

编辑:然后预期的另一个广播是发布此问题.嗯

Awa*_*yte 8

我已经通过返回preventDefault修复了这个问题

spyOn($rootScope, '$broadcast').and.returnValue({preventDefault: true})
Run Code Online (Sandbox Code Playgroud)


小智 1

问题 -

Angular 框架正在尝试调用$broadcast函数并期望从该函数返回一个具有defaultPrevented属性的对象。

但因为

spyOn( $rootScope, '$broadcast' );

块中的语句无法调用beforeEach实际实现,因此它不会返回包含属性的对象。$broadcastdefaultPrevented

解决方案 -

spyOn( $rootScope, '$broadcast' );语句从beforeEach一个块 移到it另一个块之前scope.doIt( 'test1', 'test2' );

  • 我遇到了同样的问题,并通过将间谍设置为“andCallThrough()”来修复它 (4认同)