title: Mocking a dependent service to a controller unit test in AngularJS
body: <p>I have a problem when unit testing an Ionic app. I have seen similar questions, but none solved my problem.</p>
  
  <p>Basically, this is my <strong>controller.js</strong></p>
  
  <pre><code>angular.module('starter.controllers')
  .controller('myController', function($scope, myService) {
  
      $scope.test = function() {
          return myService.getTestVariable();
      };
  
  });
  </code></pre>
  
  <p>and this is my <strong>service.js</strong></p>
  
  <pre><code>angular.module('starter.services')
  .factory('myService', function() {
  
      var self = this;
      self.testVariable = true;
  
      return {
          getTestVariable : function() {
              return self.testVariable;
          }
      };
  });
  </code></pre>
  
  <p>Modules are created in a <strong>app.js</strong> file:</p>
  
  <pre><code>angular.module('starter', ['starter.controllers', 'starter.services']);           
  angular.module('starter.services', []);
  angular.module('starter.controllers', []);
  </code></pre>
  
  <p>Now, I want to test the controller and use a mock versione of the service, so I set up the test like this:</p>
  
  <pre><code>describe('Controller: myController', function() {
      var scope, controller, serviceMock;
  
      beforeEach(function() {
          module('starter');
      });
  
      beforeEach(function () {
          serviceMock= {
              getTestVariable : function() {return true;}
          };
  
          module(function ($provide) {
              $provide.value('myService', serviceMock);
          });
      });
  
      beforeEach(inject(function($rootScope, $controller) {
          scope = $rootScope.$new();
          controller = $controller('myController', {
              $scope: scope
          });
      }));
  
      it('should work as expected', function(){
          spyOn(serviceMock, 'getTestVariable').and.callThrough();
          scope.test();
          expect(serviceMock.getTestVariable).toHaveBeenCalled();
      });
  });
  </code></pre>
  
  <p>However, when I try to run the test, it prints an error:</p>
  
  <pre><code>TypeError: 'undefined' is not a function (evaluating 'myService.getTestVariable()')
      at &lt;dir&gt;/controller.js:5
  </code></pre>
  
  <p>Why is this happening?</p>