mardi 6 janvier 2015

How do you mock an angularjs $resource factory

I have a resource factory



angular.module('mean.clusters').factory('Clusters', ['$resource',
function($resource) {
return $resource('clusters/:clusterId/:action', {
clusterId: '@_id'
}, {
update: {method: 'PUT'},
status: {method: 'GET', params: {action:'status'}}
});
}]);


and a controller



angular.module('mean.clusters').controller('ClustersController', ['$scope',
'$location', 'Clusters',
function ($scope, $location, Clusters) {
$scope.create = function () {
var cluster = new Clusters();

cluster.$save(function (response) {
$location.path('clusters/' + response._id);
});
};

$scope.update = function () {
var cluster = $scope.cluster;

cluster.$update(function () {
$location.path('clusters/' + cluster._id);
});
};


$scope.find = function () {
Clusters.query(function (clusters) {
$scope.clusters = clusters;

});
};
}]);


I am writing my unit tests and every example I find is using some form of $httpBackend.expect to mock the response from the server, and I can do that just fine.


My problems is, when unit testing my controller functions I would like to mock the Clusters object. If I'm using $httpBackend.expect, and I introduce a bug in my factory every unit test in my controller will fail.


I would like to have my test of $scope.create test only $scope.create and not also my factory code.


I've tried adding a provider in the beforeEach(module('mean', function ($provide) { part of my tests but I cant seem to get it right.


I also tried



clusterSpy = function (properties){
for(var k in properties)
this[k]=properties[k];
};

clusterSpy.$save = jasmine.createSpy().and.callFake(function (cb) {
cb({_id: '1'});
});


and setting Clusters = clusterSpy; in the before(inject but in the create function, the spy gets lost with



Error: Expected a spy, but got Function.



I have been able to get a spy object to work for the cluster.$update type calls but then it fails at var cluster = new Clusters(); with a 'not a function' error.


I can create a function that works for var cluster = new Clusters(); but then fails for the cluster.$update type calls.


I'm probably mixing terms here but, is there a proper way to mock Clusters with spies on the functions or is there a good reason to just go with $httpBackend.expect?


Aucun commentaire:

Enregistrer un commentaire