I need to test an AngularJs service that loads an image from a URL. Here is my service:
(function () {
'use strict';
function SourceLoader($q, $log) {
function loadImage(url) {
var deferred = $q.defer(),
image = new Image();
image.onload = function () {
deferred.resolve(image);
};
image.onerror = function (error) {
$log.error('Error while loading image from url ' + url);
$log.debug(error);
deferred.reject(error);
};
image.src = url;
return deferred.promise;
}
function loadImages(urls) {
var count = 0, deferred = $q.defer(),
images = [],
callback = function (image, index) {
images.insert(index, image);
count += 1;
if (count === urls.length) {
deferred.resolve(images);
}
};
urls.forEach(function (url, index) {
var image = new Image();
image.onload = function () {
callback(image, index);
};
image.onerror = function (event) {
$log.error('Error while loading image from url ' + url);
$log.debug(event);
callback(event, index);
};
image.src = url;
});
return deferred.promise;
}
return {
loadImage: loadImage,
loadImages: loadImages
};
}
var app = angular.module('myCanvasModule'),
requires = [
'$q',
'$log',
SourceLoader
];
app.factory('SourceLoaderService', requires);
}());
I use Karma with Jasmine for test suits. My test suits are something like this:
(function () {
'use strict';
describe('myCanvasModule: Services: SourceLoaderService-->\n\t', function () {
var SourceLoaderService, getTestData;
getTestData = TestUtils.getTestData.bind(null, SourceLoaderServiceTestData);
beforeEach(function () {
module('myCanvasModule');
});
beforeEach(function () {
inject(function ($injector) {
SourceLoaderService = $injector.get('SourceLoaderService');
});
});
describe('SourceLoaderService.loadImage-->\n\t', function () {
var testData;
beforeEach(function () {
testData = getTestData('loadImage');
});
it('should load the source and return the image as response', function (done) {
var image;
SourceLoaderService.loadImage(testData.validSource).then(function (response) {
image = response;
done();
console.log('called');
},function (error) {
console.log('called', error);
done();
});
});
});
});
}());
When I run the test suits, I get:
Error: Timeout - Async callback is not called within the timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
I do not know what is going wrong. I am new to Karma and Jasmine. Thanks for the help.
source
share