Testing angular controllers with Jasmine

Testing angular controllers with Jasmine

by Rimian Perkins

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="https://code.angularjs.org/1.3.5/angular.min.js"></script>
<script src="https://code.angularjs.org/1.3.5/angular-mocks.js"></script>

JavaScript

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

    myApp.controller('MyCtrl', ['$scope', '$http', function ($scope, $http) {
        var authToken;

        $http.get('/auth.py').success(function (data, status, headers) {
            authToken = headers('A-Token');
            $scope.user = data;
        });

        $scope.saveMessage = function (message) {
            var headers = {
                'Authorization': authToken
            };
            $scope.status = 'Saving...';

            $http.post('/add-msg.py', message, {
                headers: headers
            }).success(function (response) {
                $scope.status = '';
            }).error(function () {
                $scope.status = 'ERROR!';
            });
        };
    }]);
})(angular);

// ---SPECS-------------------------
describe('MyController', function () {
    var $httpBackend, $rootScope, createController, authRequestHandler;

    beforeEach(module('MyApp'));

    beforeEach(inject(function ($injector) {
        $httpBackend = $injector.get('$httpBackend');
        authRequestHandler = $httpBackend.when('GET', '/auth.py')
            .respond({
            userId: 'userX'
        }, {
            'A-Token': 'xxx'
        });

        $rootScope = $injector.get('$rootScope');

        var $controller = $injector.get('$controller');

        createController = function () {
            return $controller('MyController', {
                '$scope': $rootScope
            });
        };
    }));


    afterEach(function () {
        $httpBackend.verifyNoOutstandingExpectation();
        $httpBackend.verifyNoOutstandingRequest();
    });


    it('should fetch authentication token', function () {
        $httpBackend.expectGET('/auth.py');
        var controller = createController();
        $httpBackend.flush();
    });


    it('should fail authentication', function () {

        // Notice how you can change...