【问题标题】:angular jasmine: 'undefined' is not an object - broadcast within timeout - error角茉莉花:“未定义”不是对象-超时内广播-错误
【发布时间】:2014-12-24 08:12:55
【问题描述】:

我有这样的功能:

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

到目前为止,此功能运行良好。但是在编写测​​试时我遇到了一些麻烦。

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

        } ) );
      }
    );

这将导致以下错误:

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

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

提前感谢您的帮助。

:)

编辑:然后预期的另一个广播正在发布此问题。嗯

【问题讨论】:

  • 错误指向哪一行?冲水前还是冲水后?
  • 这似乎有点做作,所以我不确定你真正想要达到什么目的。我假设您在规范中的其他地方定义“范围”(以及被测代码中的 $scope)。您是否将 $rootScope 注入到任何地方的被测代码中?无论如何,这似乎是一种不太理想的测试方式:与其监视 $rootScope.$broadcast,不如像在普通代码中一样(即 $scope. $on)

标签: javascript angularjs testing jasmine karma-runner


【解决方案1】:

我已经通过返回 preventDefault 解决了这个问题

spyOn($rootScope, '$broadcast').and.returnValue({preventDefault: true})

【讨论】:

    【解决方案2】:

    问题-

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

    但是因为

    spyOn( $rootScope, '$broadcast' );

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

    解决方案 -

    spyOn( $rootScope, '$broadcast' ); 语句从beforeEach 块移动到 it 正好在 scope.doIt( 'test1', 'test2' ); 之前阻止。

    【讨论】:

    • 我遇到了同样的问题并通过将间谍设置为'andCallThrough()'来解决它
    • @Katana24 你为我节省了很多时间,非常感谢!
    • +1 这解决了我的问题。一个单独的测试抛出了奇怪的广播错误。将间谍移动到它修复它。
    猜你喜欢
    • 2015-04-24
    • 2016-10-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-15
    • 1970-01-01
    • 2015-11-26
    • 2016-05-28
    • 2018-06-26
    相关资源
    最近更新 更多