Last active
December 22, 2015 17:59
-
-
Save sebv/6509524 to your computer and use it in GitHub Desktop.
Fixture service for angular unit test
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict'; | |
angular.module('fixtureApp', []); | |
angular.module('fixtureApp') | |
.service('Fixtures', function($http, $q) { | |
var BASE_URL = ('/base/test/fixtures/'); | |
var fixtures = {}; | |
return { | |
// Returns a promise getting the fixture on demand. | |
get: function(filename) { | |
var deferred = $q.defer(); | |
$http.get(BASE_URL + filename).success(function(data) { | |
deferred.resolve(data); | |
}).error(function(data, status) { | |
deferred.reject({ | |
fixture: filename, | |
message: data, | |
status: status | |
}); | |
throw new Error('Cannot get fixture ' + filename + ' ' + status + ' ' + data ); | |
}); | |
return deferred.promise; | |
}, | |
// Retrieves the necessary fixtures. | |
prefetch: function() { | |
var promises = []; | |
_(fixtures).each(function(promise, filename){ | |
promises.push(promise); | |
promise.then(function(data) { | |
fixtures[filename] = data; | |
}); | |
}, this); | |
return $q.all(promises); | |
}, | |
// Wraps the get call within a function to be used to configure | |
// ngMock $httpBackend. | |
// prefetch need to be called before fixture is consumed. | |
wrappedGet: function(filename) { | |
fixtures[filename] = this.get(filename); | |
return function() { | |
return [200, fixtures[filename]]; | |
}.bind(this); | |
}, | |
// Removes all the cached fixtures | |
clear: function() { | |
fixtures = {}; | |
} | |
}; | |
}); | |
var injector = angular.injector(['ng','fixtureApp']); | |
window.Fixtures = injector.get('Fixtures'); |
Yes you are right, but I had in mind to expose a getPromise method as well, it's why I was unwrapping the response object. See latest version.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
You don't need your own deferred objects here. $http returns promises for you already: