Skip to content

Instantly share code, notes, and snippets.

@sebv
Last active December 22, 2015 17:59
Show Gist options
  • Save sebv/6509524 to your computer and use it in GitHub Desktop.
Save sebv/6509524 to your computer and use it in GitHub Desktop.
Fixture service for angular unit test
'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');
@petebacondarwin
Copy link

You don't need your own deferred objects here. $http returns promises for you already:

_(fixtures).keys().each(function(filename){
  var promise = $http.get(BASE_URL + filename).then(function(response) {
    fixtures[filename] = response.data;
  }, function(response) {
    throw new Error('Cannot get fixture ' + filename + ' ' + status + ' ' + data );
  });
  promises.push(deferred.promise);
});

@sebv
Copy link
Author

sebv commented Sep 11, 2013

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