# Angular directive test

I'm learning how to write tests in Angular (these are my first tests in general). There are a lot of tutorials out there but each one of them has a different approach. I'm a bit confused if I'm doing things the right way.

I made a simple directive for testing purposes and I've called it tooltip (though its not really a tooltip).

tooltip.js:

angular.module('mytestapp', []);

(function(){
angular.module('mytestapp').directive('tooltip', tooltip);

function tooltip() {
var directive = {
controller: tooltipCtl,
controllerAs: 'vm',
restrict: 'E',
template:
"<span>This is a tooltip for {{ name }}</span>" +
"<button ng-click='vm.myFun()'>Click me!</button>",
scope: {
name: '@'
},
};

return directive;

}

function tooltipCtl() {
var vm = this;

vm.things = 3;

vm.myFun = myFun;
function myFun() {
vm.age = 30;
}
}

})();


tooltip.spec.js:

describe('tooltip', function () {
angular.mock.module('mytestapp');
beforeEach(angular.mock.module('mytestapp'));

describe('template', function () {
var $compile; var$scope;
var element;
var controller;
// beforeEach(module('templates'));

beforeEach(inject(function(_$compile_, _$rootScope_) {
$compile = _$compile_;
scope = _$rootScope_.$new();
element = angular.element("<tooltip name='john'></tooltip>");
element = $compile(element)(scope); scope.$digest();
}));

beforeEach(function () {
controller = element.controller('tooltip');
});

it('should have name equal to john', function (){
expect(element.html()).toContain('john');
});

it('should have 3 items', function (){
expect(controller.things).toBe(3);
});

it('should set age when clicked to 30', function () {
expect(controller.myFun).toBeDefined();
controller.myFun();
expect(controller.age).toBe(30);
});

});
});


I'm using Karma and Jasmine, Angular 1.4.7, angular-mocks and ng-html2js. I'd be thankful for a general review of my code. Links to some good, up-to-date guides would help as well.

1. I have ng-html2js included but I didn't really use it, can I use it in my example? Should I do it? Yes/no, and why?
2. I have a beforeEach(module('templates')); that I've used in some previous example but my spec works without it here. Is this module-templates things something common, or is there some sort of pattern where you use it?
3. I've used angular.mock.module but my spec works fine with just module. Any tips here?

1. You don't really need to use ng-html2js since you don't really have a file .html file.

3. You can just use angular.mock.module if you want. I usually use this pattern for my tests.

Example:

const angular = window.angular,
expect = window.chai.expect,
sinon = window.sinon;

const inject = angular.mock.inject,
module = angular.mock.module;


I have a repo with some patterns for unit testing. Feel feel to take a look at it.