jasmine-angular: test a Controller with $scope

test a Controller with $scope

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 MyService() {
    this.greet = function(name) {
      return 'hello ' + name;
    }
  }

  function MyController($scope, MyService) {
    $scope.greetUpperCase = function(name) {
      return MyService.greet(name).toUpperCase();
    }
  }
  angular.module('MyModule', [])
    .service('MyService', MyService)
    .controller('MyController', ['$scope', 'MyService', MyController]);
})();


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

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

  it("test greetUpperCase()", function() {
    var $scope = $rootScope.$new();
    $controller("MyController", {
      $scope: $scope
    });
    expect($scope.greetUpperCase('bob')).toBe('HELLO BOB');
  });
});