I am writing unit test for $interval. The code is like this: angular.module('serviceInvoker', []).
run(function($rootScope, $http, $interval, DateTimeFormatter) {
$rootScope.loadData = function(serviceName, dataName) {
$http.get(serviceName)
.then(function(result) {
serviceSuccessFunc(result, dataName)
})
.catch(function(error) {
serviceErrorFunc(error, dataName)
});
$rootScope.current = moment().toISOString();
$rootScope.now = moment($rootScope.current).format(DateTimeFormatter.DayHoursFormat);
};
$rootScope.autoRefresh = function(serviceName, dataName, interval) {
$interval(function() {
$rootScope.loadData(serviceName, dataName)
}, interval);
};
var serviceSuccessFunc = function(result, dataName) {
$rootScope[dataName] = result.data;
};
var serviceErrorFunc = function(error, dataName) {
$rootScope[dataName] = error;
};
});
The test code is like this:
describe('serviceInvoker', function() {
beforeEach(module('serviceInvoker'));
beforeEach(module(function($provide) {
$provide.value('DateTimeFormatter', {
DayHoursFormat: 'HH:mm'
});
$provide.value('serviceSuccessFunc', jasmine.createSpy());
$provide.value('serviceErrorFunc', jasmine.createSpy());
}));
var $interval;
beforeEach(inject(function (_$rootScope_, _$interval_, _serviceSuccessFunc_, _serviceErrorFunc_) {
$rootScope = _$rootScope_;
scope = $rootScope.$new();
$interval = _$interval_;
serviceSuccessFunc = _serviceSuccessFunc_;
serviceErrorFunc = _serviceErrorFunc_;
}));
describe("loadData function ", function () {
it("should expose loadData function to $rootScope", function () {
expect(angular.isFunction($rootScope.loadData)).toBe(true);
});
it("should be called", inject(function($http) {
spyOn($rootScope, 'loadData');
$rootScope.loadData('service', 'data');
expect($rootScope.loadData).toHaveBeenCalledWith('service', 'data');
}));
});
describe("autoRefresh function ", function () {
it("should expose autoRefresh function to $rootScope", function () {
expect(angular.isFunction($rootScope.autoRefresh)).toBe(true);
});
it("should be called", function() {
var $intervalspy = jasmine.createSpy('$interval', $interval);
spyOn($rootScope, 'autoRefresh').and.callThrough();
$rootScope.autoRefresh('service', 'data','interval');
expect($rootScope.autoRefresh).toHaveBeenCalledWith('service', 'data', 'interval');
expect($intervalspy).toHaveBeenCalled();
// expect($intervalspy).toHaveBeenCalledWith(jasmine.any(Function), 1000);
});
});
});
But there is an error for interval: Error: Expected spy $interval to have been called.
I don't know how to write unit test for interval which is inside a function(in a run block), can anyone give me some help?