我有以下angularjs服务,我想进行单元测试:
angular.module("services")
.factory("imageService", function($q)
{
var load = function(options)
{
var deferred = $q.defer();
var image = new Image();
image.onload = function()
{
deferred.resolve(image.width);
};
image.src = options.imageSource;
return deferred.promise;
};
return {
load: load
};
});
我的单元测试如下:
describe("imageService", function()
{
beforeEach(module("services"));
beforeEach(function()
{
inject(function($injector)
{
imageService = $injector.get("imageService");
});
});
it("should return image width", function(done)
{
imageService.load({
imageSource: "data:image/jpeg;base64,/9j/4AAQSkZJRgABAQEASABIAAD//gATQ3JlYXRlZCB3aXRoIEdJTVD/2wBDAAMCAgMCAgMDAwMEAwMEBQgFBQQEBQoHBwYIDAoMDAsKCwsNDhIQDQ4RDgsLEBYQERMUFRUVDA8XGBYUGBIUFRT/2wBDAQMEBAUEBQkFBQkUDQsNFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBQUFBT/wgARCAACAAIDAREAAhEBAxEB/8QAFAABAAAAAAAAAAAAAAAAAAAACP/EABQBAQAAAAAAAAAAAAAAAAAAAAD/2gAMAwEAAhADEAAAAVSf/8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABBQJ//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAwEBPwF//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAgEBPwF//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQAGPwJ//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPyF//9oADAMBAAIAAwAAABCf/8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAwEBPxB//8QAFBEBAAAAAAAAAAAAAAAAAAAAAP/aAAgBAgEBPxB//8QAFBABAAAAAAAAAAAAAAAAAAAAAP/aAAgBAQABPxB//9k="
})
.then(function(width)
{
expect(width).to.equal(2);
done();
});
});
});
我遇到的问题是onload调用是异步的,通常你会在调用后使用$timeout.flush()
来刷新延迟的任务,但是因为加载图像需要一些时间,所以你不能刷新调用函数后的任务,因此永远不会调用done()
函数导致测试失败。
使用的图书馆: