AngularJS-带$timeout的单元测试
我有一个如下的指令:AngularJS-带$timeout的单元测试,angularjs,unit-testing,jasmine,karma-jasmine,Angularjs,Unit Testing,Jasmine,Karma Jasmine,我有一个如下的指令: angular.directive('myDirective', ['$compile','$timeout', function($compile,$timeout){ console.log("myDirective compile"); return { link: function(scope, element) { console.log("myDirective before timeout");
angular.directive('myDirective', ['$compile','$timeout', function($compile,$timeout){
console.log("myDirective compile");
return {
link: function(scope, element) {
console.log("myDirective before timeout");
$timeout(function(){
console.log("myDirective after timeout");
});
}
};
}]);
当我使用Karma Jasmine进行单元测试时,我会在超时之前获得myDirective compile
和myDirective的LOG
输出。但超时后,myDirective没有输出
如何让$timeout
函数在单元测试中运行?使用
$timeout.flush(amount)
在测试中,使用amount
您希望通过的时间量。您可以使用$timeout
服务上的flush
方法刷新您设置的超时
请注意,这在ngMock中可用,因此需要包括角度模拟。(我很肯定你有,但只是以防万一。)
有关示例,请参见下面的测试
describe('my directive test', function () {
var element;
var scope;
beforeEach(module('myApp'));
beforeEach(inject(function($compile, $rootScope){
element = '<my-directive></my-directive>';
scope = $rootScope.$new();
element = $compile(element)(scope);
scope.$digest();
spyOn(console, 'log').and.callThrough();
}));
it('should not log the timeout', inject(function ($timeout) {
expect(console.log).not.toHaveBeenCalledWith('myDirective after timeout');
}));
it('should log after timeout', inject(function ($timeout) {
$timeout.flush();
expect(console.log).toHaveBeenCalledWith('myDirective after timeout');
}));
});
描述('my directive test',函数(){
var元素;
var范围;
在每个模块之前(模块(‘myApp’);
beforeach(注入函数($compile,$rootScope){
元素=“”;
scope=$rootScope.$new();
元素=$compile(元素)(范围);
范围。$digest();
spyOn(控制台,'log')。和.callThrough();
}));
它('不应记录超时'),注入(函数($timeout){
expect(console.log).not.tohavencalledwith('myDirective after timeout');
}));
它('should log after timeout',inject(函数($timeout){
$timeout.flush();
expect(console.log).tohavencalledwith('myDirective after timeout');
}));
});