I am trying to understand how to test my code with jasmine and angularJS. I wrote a test project with a controller and an injected service. Now i want to test the controller and
You should use $provide.value
in order to replace the original service instance with a mocked one:
beforeEach(module(function($provide) {
var service = {
Arrive: function (firstname, lastname) {
if (firstname && lastname) {
return true;
}
}
};
$provide.value('MyService', service);
}));
I really don't know why $provide.value
works but $provide.factory
doesn't. I'll try to take a look at the Angular code later so I can figure it out. I'll update this answer if I find out something.
About spies, you should use them if you want to test that your mocks are being used the way they are supposed to. That includes checking parameters and invocations. Here's your code changed to use a spy:
it('checks that Arrived is correctly used', function() {
// Arrange
spyOn(service, 'Arrive');
// Act
scope.Arrived('Franz', 'Kafka');
// Assert
expect(service.Arrive).toHaveBeenCalledWith('Franz', 'Kafka');
});
Here's your fixed jsFiddle.