AngularJS - interval not resetting
I have an angular service function that I'm ready to test:
doSomeTask: function (ids, callback) {
$http.put('/get_job', {'ids': ids}).success(function (data) {
var statusCheck = $interval(function() {
$http.get('check_status?=' + data.job_id).success(function (data) {
if(data.completed) {
$interval.cancel(statusCheck);
// and do something...
}
});
}, 2000);
});
And the next test for it:
describe('MyService', function() {
var myService;
var $httpBackend;
var $interval;
beforeEach(module('myModule'));
beforeEach(inject(function(_$httpBackend_, _$interval_, $rootScope, MyService) {
$httpBackend = _$httpBackend_;
$interval = _$interval_;
myService = MyService;
}));
describe('doSomeTask', function () {
beforeEach(function () {
$httpBackend.expectPUT("/get_job").respond({ job_id: '123' });
$httpBackend.expectGET("/status_check").respond({ completed: true });
});
it('should do it well', inject(function ($interval) {
var ids = [1,2,3];
myService.doSomeTask(ids);
$httpBackend.flush();
$interval.flush();
}));
});
});
It seems that my interval never flashes (the second wait will never be satisfied, and my breakpoints inside the interval never fire). I also feel like I'm using mock (put some in flush support). The angular and mocks versions are the same ...
What am I doing wrong? How can I clear my interval?
source to share
I think you need to call the second one $httpBackend.flush()
after you reset your interval. Test if you get console output when you execute the log at this point in your code:
doSomeTask: function (ids, callback) {
$http.put('/get_job', {'ids': ids}).success(function (data) {
var statusCheck = $interval(function() {
console.log("flushed");
$http.get('check_status?=' + data.job_id).success(function (data) {
if(data.completed) {
$interval.cancel(statusCheck);
// and do something...
}
});
}, 2000);
});
When you get flushed
in your console, then call the second $httpBackend.flush()
one and the second HTTP request will fire.
it('should do it well', inject(function ($interval) {
var ids = [1,2,3];
myService.doSomeTask(ids);
$httpBackend.flush();
$interval.flush();
// after this call, you should get a 'flushed' in your console
$httpBackend.flush();
// after this call, the second http should fire
}));
Decision:
To clear the interval, specify the number of milliseconds you want to reset like so: $interval.flush(2000)
source to share