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: '@'
},
link: link
};
return directive;
function link(scope, elem, attrs) {}
}
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.
Additional questions:
- 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?
- 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? - I've used
angular.mock.module
but my spec works fine with justmodule
. Any tips here?