/angularjs/

AngularJS Unit Test - part 1

2014-07-05 14:57:58

Test scope

about.controller.js

'use strict';

angular.module('angularJsYoApp')

    .controller('AboutCtrl', function ($scope) {
        $scope.content = 'Some desc about this project ...';
    })
;

about.controller.test.js

'use strict';

describe('Controller: AboutCtrl', function () {

    beforeEach(module('angularJsYoApp'));

    var AboutCtrl,
        scope;

    beforeEach(inject(function ($controller, $rootScope) {
        scope = $rootScope.$new();
        AboutCtrl = $controller('AboutCtrl', {
            $scope: scope
        });
    }));

    it('should contain not null content', function () {
        expect(scope.content).toBeDefined();
        expect(scope.content).not.toBeNull();
    });
});

Test method from controller

menu.controller.js

'use strict';

angular.module('angularJsYoApp')

    .controller('MenuCtrl', function ($scope, $location) {
        $scope.getClass = function(path) {
            if ($location.path().substr(0, path.length) === path) {
                return 'active';
            } else {
                return '';
            }
        };
    })
;

manu.controller.test.js

'use strict';

describe('Controller: ManuCtrl', function () {

    beforeEach(module('angularJsYoApp'));

    var MenuCtrl,
        scopeMock,
        locationMock;

    beforeEach(inject(function ($controller, $rootScope) {

        locationMock = {
            mpath:'',
            setPath: function(path) { this.mpath = path;},
            path: function(){return this.mpath;}
        }

        scopeMock = $rootScope.$new();

        MenuCtrl = $controller('MenuCtrl', {
            $scope: scopeMock,
            $location: locationMock
        });
    }));

    it('should return "active" if current path is the same as menu item', function () {
        locationMock.setPath('home');
        expect(scopeMock.getClass('home')).toBe("active");

        locationMock.setPath('post');
        expect(scopeMock.getClass('post')).toBe("active");
    });
});

GitHub