Injected Service Test Controller Inside JS Corner JS

I am trying to figure out how to test my code with jasmine and angularJS. I wrote a test project with a controller and an injectable service. Now I want to test the controller and try to make fun of the entered service. But I did not find a way to check the "Arrived" function from my controller. Heres my jsfiddle: http://jsfiddle.net/2fwxS/

controller.js:

angular.module('myApp.controllers', []) .controller('MyCtrl', ['$scope', 'MyService', function ($scope, MyService) { $scope.User = {}; $scope.HasUserArrived = false; $scope.Arrived = function(firstname, lastname) { $scope.HasUserArrived = MyService.Arrive(firstname, lastname); return $scope.HasUserArrived; } }]); 

services.js:

 var myApp = angular.module('myApp.services', []). value('version', '0.1'); myApp.factory('MyService', [function () { return { HasArrived: false, Arrive: function (firstname, lastname) { this.HasArrived = false; if (firstname && lastname) { this.HasArrived = true; } console.log("User has arrived: " + this.HasArrived); return this.HasArrived; } } }]); 

I found several similar explanations in which $ provision might be the right solution ( How can I write a jasmine test for an angular controller and a service like this? ) Or createSpy ( How do you mock the angular service, which is a function? ), But I couldn’t understand when i need $ provider.factory or $ provider.value or when i use createSpy?

I would appreciate if someone could help me understand the differences and get the deactivated code in my jsFiddle ( http://jsfiddle.net/2fwxS/ ) up and down ...

+8
angularjs tdd testing code-injection jasmine
source share
1 answer

You should use $provide.value to replace the original instance of the service with a laughable 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 not. I will try to take a look at Angular code later to figure this out. I will update this answer if I find out something.

About spies, you should use them if you want to verify that your uterus is used the way they should. This includes checking parameters and calls. Here your code has changed to spy usage:

 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 is your fixed jsFiddle .

+10
source share

All Articles