jasmine-angular: jasmine.createSpyObj

Test angular using jasmine.createSpyObj

by ronapelbaum

HTML

<script src="https://jasmine.github.io/2.4/lib/jasmine.js"></script>
<script src="https://jasmine.github.io/2.4/lib/jasmine-html.js"></script>
<script src="https://jasmine.github.io/2.4/lib/boot.js"></script>
<link rel="stylesheet" href="https://jasmine.github.io/2.4/lib/jasmine.css">
<script src="https://code.angularjs.org/1.4.9/angular.js"></script>
<script src="https://code.angularjs.org/1.4.9/angular-mocks.js"></script>

JavaScript

//--------------BL------------
(function() {
  function MyDataService() {
    this.getName = function() {
      return 'bob';
    }
  }

  function MyController(MyDataService) {
    this.greet = function() {
      return 'hello ' + MyDataService.getName();
    }
  }

  angular.module('MyModule', [])
    .service('MyDataService', MyDataService)
    .controller('MyController', ['MyDataService', MyController]);

})();


//--------------specs------------
describe("MyController test suite", function() {
  var $controller;
  beforeEach(module('MyModule'));

  beforeEach(inject(function(_$controller_) {
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $controller = _$controller_;
  }));

  it("test greet() - expect spyObj.getName() to have been called", function() {
      var spyObj = jasmine.createSpyObj('MockService', ['getName']);
      var ctrl = $controller("MyController", {
        MyDataService: spyObj
      });
      ctrl.greet();
      expect(spyObj.getName).toHaveBeenCalled();
  });
  
  it("test greet() - mock spyObj.getName() to return 'alice", function() {
      var spyObj = jasmine.createSpyObj('MockService', ['getName']);
      spyObj.getName.and.returnValue('alice');
      
      var ctrl = $controller("MyController", {
        MyDataService: spyObj
      });
      expect(ctrl.greet()).toBe('hello alice');
  });

});