我正在尝试测试超时,但我在元素的范围方面遇到了问题。我是编写 JS 测试的新手。
在 it('shouldhavetimerdefineatstart')
测试中,我的变量记录为未定义。这是为什么?
我认为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();
})
也许我测试不正确?
最佳答案
您需要调用
beforeEach(module('plunker'));
在“测试超时”描述 block 中。您只是在另一个描述 block 中调用它
关于javascript - AngularJS Jasmine 测试 - 元素隔离范围未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37997387/