ng test ctrl w/Service

Testing angular controllers with Jasmine

by mckennatim

HTML

<script src="http://jasmine.github.io/1.3/lib/jasmine.js"></script>
<script src="http://jasmine.github.io/1.3/lib/jasmine-html.js"></script>
<link rel="stylesheet" href="http://jasmine.github.io/1.3/lib/jasmine.css">
<script src="http://code.angularjs.org/1.2.9/angular.js"></script>
<script src="http://code.angularjs.org/1.2.9/angular-mocks.js"></script>

JavaScript

//--- CODE --------------------------
(function (angular) {
    // Create module
    var myApp = angular.module('myApp', []);

    myApp.controller('MyCtrl', ['$scope', function ($scope) {
        $scope.name = 'Superhero';
        $scope.counter = 0;
        $scope.$watch('name', function (newValue, oldValue) {
            $scope.counter = $scope.counter + 1;
        });
    }]);
    myApp.controller('AnCtrl', ['$scope', 'Service', function ($scope, Service) {
        $scope.duck = Service.getDuck();
    }]);
    
})(angular);



// ---SPECS-------------------------

describe('myApp', function () {
    var scope,
    ctrl;
    beforeEach(function () {
        module('myApp');
    });

    describe('MyCtrl', function () {
        beforeEach(inject(function ($rootScope, $controller) {
            scope = $rootScope.$new();
            controller = $controller('MyCtrl', {'$scope': scope});
        }));
        it('sets the name', function () {
            expect(scope.name).toBe('Superhero');
        });

        it('watches the name and updates the counter', function () {
            expect(scope.counter).toBe(0);
            scope.name = 'Batman';
            scope.$digest();
            expect(scope.counter).toBe(1);
        });
    });
    describe('AnCtrl', function () {
        beforeEach(inject(function ($rootScope, $controller) {
            Service = {
                getDuck: function(){
                    return 'Daffy';
                }
            };
            scope = $rootScope.$new();
            ctrl = $controller('AnCtrl', {'$scope': scope, Service: Service});
        }));
        it('duck shouldbe Daffy', function(){
            expect(scope.duck).toBe('Daffy');
        });
    });
    describe('AnCtrl 2', function () {
        beforeEach(module('myApp', function($provide) {
            service = {
                getDuck: function(){}
            };            
            spyOn(service, 'getDuck').andReturn('Daffy');
           ...