mercredi 4 février 2015

Angular unit test factory that inherits from $resource

I'm actually overriding the way $resource works, by extending it using the following code :



'use strict';

angular
.module('Exo.api')
.factory('Resource', function ($resource) {
Resource = function (url, params, methods) {
defaults = {
update: { method: 'PATCH' },
create: { method: 'POST' }
}

methods = angular.extend(defaults, methods);
resource = $resource(url, params, methods);

resource.prototype.$save = function () {
var action = !this.id ? '$create' : '$update';
return this[action]();
};

return resource;
}
return Resource;
)


However, I have a hard time to test it and to be honest, don't know where to start exactly.


What I did so far is :



'use strict';

describe('Exo.api.Resource', function () {
Resource = {}
User = {}

beforeEach(module('Exo.api'));
beforeEach(inject(function (_Resource_) {
Resource = _Resource_;
User = Resource('/users/:id', { id: '@id' })
}));

it('should be defined', function () {
expect(Resource).toBeDefined();
});

describe('$save', function () {
beforeEach(function () {
spyOn(Resource, '$update');
spyOn(Resource, '$create');
});

describe('when object has an id', function () {
it('should have call the $update method', function () {
user = new User({ id: 1, name: 'Chuck Norris' });
user.$save()
expect(Resource.$update).toHaveBeenCalled();
});
});

describe('when object does not have an id', function () {
it('should have call the $create method', function () {
user = new User({ name: 'Chuck Norris' });
user.$save()
expect(Resource.$create).toHaveBeenCalled();
});
});
});
});


Unfortunately, this is not working at all. Any help? Thanks


Aucun commentaire:

Enregistrer un commentaire