我有这样一个函数:
$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/