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功能和测试它工作正常.
在此先感谢您的帮助.
:)
编辑:然后预期的另一个广播是发布此问题.嗯
我已经通过返回preventDefault修复了这个问题
spyOn($rootScope, '$broadcast').and.returnValue({preventDefault: true})
Run Code Online (Sandbox Code Playgroud)
小智 1
问题 -
Angular 框架正在尝试调用$broadcast
函数并期望从该函数返回一个具有defaultPrevented属性的对象。
但因为
spyOn( $rootScope, '$broadcast' );
块中的语句无法调用beforeEach
实际实现,因此它不会返回包含属性的对象。$broadcast
defaultPrevented
解决方案 -
将spyOn( $rootScope, '$broadcast' );
语句从beforeEach
一个块
移到it
另一个块之前scope.doIt( 'test1', 'test2' );
。
归档时间: |
|
查看次数: |
3622 次 |
最近记录: |