【发布时间】:2016-06-24 01:14:09
【问题描述】:
我正在尝试测试超时,但我遇到了元素范围的问题。我是编写 JS 测试的新手。
在it( 'should have timer defined at start' ) 测试中,我的变量记录为未定义。这是为什么?
我认为isolateScope() 会将指令的范围拉进去?
我的测试如下所示:
https://plnkr.co/edit/IMrPd9g6HFSkgHizFF9p?p=preview
describe( 'Testing timeout', function(){
var scope, $timeout, element;
beforeEach(inject( function ($rootScope, $compile, _$timeout_, $injector ){
scope = $rootScope.$new();
$timeout = _$timeout_;
scope.onWarning = function(){
scope.warned = true;
};
element = '<div timeout on-warning="onWarning" on-timeout="onTimeout"></div>';
element = $compile(element)(scope);
scope.$apply();
scope.$digest();
}));
it( 'should have timer defined at start', function(){
console.log( element.isolateScope() , scope )
expect( element.isolateScope().timeoutService.timer ).not.toBeFalsy;
});
it( 'should have run warning function', function(){
$timeout.flush( 5000 );
expect( scope.warned ).toBe( true );
});
});
我的指令如下所示:
app.directive( 'timeout', function( timeoutService ){
return {
restrict: "A",
scope: {
onWarning: "&", // what function to fire when showing a warning
},
link: function( scope, elem, attr ){
scope.timeoutService = timeoutService;
if( !scope.onWarning ){
throw new Error( "Must provide on-warning for timeout directive." );
}
//console.log( scope.onWarning, scope.onTimeout );
// register timeouts and warnings with the service
timeoutService.onWarning = scope.onWarning;
}
}
});
app.service( 'timeoutService', function( $timeout ){
var _this = this;
var timer = null;
var time = 5000;
this.startTimer = function(){
timer = $timeout( function(){
if( _this.onWarning ){
_this.onWarning()();
}
}, time)
}
this.startTimer();
})
也许我测试不正确?
【问题讨论】:
标签: javascript angularjs unit-testing jasmine