I have a code which instantiate a new object from $resource Api.User = $resource(...blahblah...)
that I'm using as :
'use strict';
angular
.module('Exo.users')
.controller('UsersCreateCtrl', function (collection, Api, FormRemoteErrors, $modalInstance) {
var vm = this;
vm.user = new Api.user({ name: '' });
vm.save = function (isValid) {
vm.submitted = true;
if (isValid) {
vm.saving = true;
vm.user.$save().then(function (user) {
collection.push(user);
$modalInstance.close(true);
}, function (errors) {
vm.saving = false;
});
}
};
});
As you can see, there is a save
function in which I'm calling vm.user.$save
in order to save the new user. I need some help in order to be able to test it.
In my specs, I first try to mock the Api.User object along with the $save function :
beforeEach(module('Exo.users', function ($provide) {
Api = {
User: jasmine.createSpy('User').and.returnValue(function () {
name: '',
$save: jasmine.createSpy()
});
}
$provide.value('Api', Api);
}));
it('create a new user with an empty name', function () {
expect(scope.user.name).toEqual('');
});
it('calls the $save method on user instance', function () {
scope.save(true);
expect(scope.user.$save).toHaveBeenCalled();
});
Unfortunately, I've got the following error :
TypeError: 'undefined' is not an object (evaluating 'vm.user.$save().then')
I understand that I need to mock the then
function but how to do it and how to also test what happen when the promise succeed or fails? I know that this question has been asked already but somehow I cannot find any relevant answers.
Aucun commentaire:
Enregistrer un commentaire