javascript - Angular Jasmine : 'undefined' is not an object - broadcast within timeout - error

标签 javascript angularjs testing jasmine karma-runner

我有这样一个函数:

 $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' is not an object (evaluating '$rootScope.$broadcast('$locationChangeStart', newUrl, oldUrl, $location.$$state, oldState).defaultPrevented')

为什么?我做错了什么? 在函数中没有 $timeout 并测试它工作正常。

在此先感谢您的帮助。

:)

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

最佳答案

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

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

关于javascript - Angular Jasmine : 'undefined' is not an object - broadcast within timeout - error,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27633683/

相关文章:

javascript - 如何根据手势滚动网页。手部 Action

javascript - 如何将连续包含多个字段的数组更改为只有一个字段的数组?

Angularjs - 单击按钮时水平滚动

C#/.NET 如何在单例中测试 protected 方法?

python - 我如何在 python 中实现此功能?

ruby - 使用 Ruby 的 WIN32API 查找特定按钮

javascript - 如何连续搜索现有文档并相应地修改/添加每个文档?

javascript - 传入表单数据没有给出响应

javascript - Angular 和 JS 过滤非标准复选框行为

angularjs - 更改动态加载的 SVG 的颜色