Javascript Testng AngularJS中部分执行的$timeout
我有一个AngularJS服务。此服务在其功能中使用$timeout。我试图找出如何在各种情况下测试此服务。这是我的密码:Javascript Testng AngularJS中部分执行的$timeout,javascript,angularjs,Javascript,Angularjs,我有一个AngularJS服务。此服务在其功能中使用$timeout。我试图找出如何在各种情况下测试此服务。这是我的密码: myApp.factory('myService', ['$timeout', function($timeout) { var isRunning = false; var myTimer = null; return { myTimer: myTimer, isRunning: isRunning, execute: functi
myApp.factory('myService', ['$timeout', function($timeout) {
var isRunning = false;
var myTimer = null;
return {
myTimer: myTimer,
isRunning: isRunning,
execute: function(time) {
this.isRunning = true;
this.myTimer = $timeout(
function() {
this.isRunning= false;
this.myTimer= null;
},
time
);
}
};
}]);
现在,我正在尝试测试这段代码。我写了以下内容:
describe('myService', function () {
var myService = null;
var $timeout = null;
var $rootScope = null;
beforeEach(inject(function (_$timeout_, _$rootScope_, _myService_) {
myService = _myService_;
$timeout = _$timeout_;
$rootScope = _$rootScope_;
}));
it('should run for one second', function() {
myService.execute(1000);
$timeout.flush();
$rootScope.$digest();
expect(myService.isRunning).toBe(false);
});
});
测试“有效”。然而,如果7.5亿秒已经过去,我希望
myService.isRunning
是true
。但是,我不知道如何测试该场景。有人能告诉我如何测试这种情况吗?谢谢您可以使用$timeout.flush
方法模拟一定时间的流逝。该方法采用一个名为delay的可选参数。文档中对此进行了解释。考虑到这一点,您可以编写如下所示的测试:
it('should run for one second', function() {
myService.execute(1000);
$timeout.flush(750);
$rootScope.$digest();
expect(myService.isRunning).toBe(true);
});