【发布时间】: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