Last active
August 29, 2015 14:27
-
-
Save felansu/02187e7d82dfdf62268f to your computer and use it in GitHub Desktop.
[AngularJS] - Testes com Karma
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
OBJETIVO DOS ESTUDOS | |
Saber aplicar testes unitários em projetos AngularJS para agregar valor ao produto e principalmente garantir que as funcionalidades estejam sendo executadas corretamente. | |
INTRO | |
O Karma possui um arquivo de configuração chamado karma.conf.js. Este arquivo permite ao Karma conhecer seu projeto, definir a ordem em que os testes são executados. | |
Aqui são especificadas as opções de configurações disponíveis no karma: LINK | |
EXEMPLOS Test Controller | |
Suponhamos que temos um controller de nome zgProgressPanelCtrl com este método: | |
vm.percentageCompleted = function () { | |
var completed = vm.completed; | |
if (!completed) { | |
return 0; | |
} else { | |
return (completed / vm.total) * 100; | |
} | |
}; | |
O teste seria realizado da seguinte forma: | |
describe('zgProgressPanelCtrl', function () { | |
var $rootScope, | |
$scope, | |
controller; | |
beforeEach(function () { | |
module('conciliacao'); | |
inject(function ($injector) { | |
$rootScope = $injector.get('$rootScope'); | |
$scope = $rootScope.$new(); | |
controller = $injector.get('$controller')('zgProgressPanelCtrl', {$scope: $scope}); | |
}); | |
}); | |
describe('Function percentage completed', function () { | |
it('Should return 0 if not define value for the completed var', function () { | |
expect(controller.percentageCompleted()).toBe(0); | |
}); | |
it('Should return 80 if total is 100 and completed is 80', function () { | |
controller.total = 100; | |
controller.completed = 80; | |
expect(controller.percentageCompleted()).toBe(80); | |
}); | |
}); | |
Na linha 11 declaramos que queremos utilizar o controller zgProgressPanelCtrl (na linha 4 foi declarada a variável controller). | |
Após disto já teremos o nosso controller injetado e a disposição do teste. | |
Veja que na linha 17 consigo chamar o método que fica no controlador ! | |
Test Directive | |
Para realizar os testes das diretivas é bem semelhante com a anterior. | |
Suponhamos que temos uma diretiva com o nome zgTitle com o seguinte template: <h4>{{zgTitle.title}}</h4> | |
A diretiva é a seguinte: | |
angular.module('teste',[]) | |
.directive('zgTitle', function () { | |
return { | |
restrict: 'E', | |
scope: { | |
title: '@' | |
}, | |
templateUrl: 'main/javascript/directives/zg-title.tpl.html' | |
}; | |
}); | |
O teste para esta diretiva será o seguinte: | |
describe("Directive: zg-title, unit tests", function () { | |
var element, $scope; | |
beforeEach(module("test", "zg.templates")); | |
beforeEach(inject(function ($compile, $rootScope) { | |
$scope = $rootScope.$new(); | |
element = angular.element("<zg-title title='Esto es una directiva fantástica !'></zg-title>"); | |
$compile(element)($scope); | |
$scope.$digest(); | |
})); | |
it('Should display the title text', function () { | |
expect(element.find("h4").text()).toBe('Esto es una directiva fantástica !'); | |
}); | |
Perceba que na linha 3 foi definido o ‘zg.templates’, ele é um preprocessor que é declarado no arquivo de configuração do Karma. Neste caso estamos utilizando o html2js. | |
preprocessors: { | |
'main/**/*.html' : 'ng-html2js' | |
}, | |
ngHtml2JsPreprocessor: { | |
moduleName: 'zg.templates' | |
}, | |
Isto processará todos os arquivos definidos na opção de configuração Files | |
Test Services | |
Os testes de serviço são bem semelhantes com os de controllers. | |
Criação de um serviço: | |
angular | |
.module('test') | |
.service('userService', userService); | |
function userService() { | |
var vm = this; | |
vm.usuarios = [ | |
{ | |
"id": 1, | |
"name": "felansu" | |
} | |
]; | |
vm.getUsers = function () { | |
return vm.usuarios; | |
}; | |
} | |
}; | |
Exemplo de teste de serviço: | |
describe('Service: userService, unit tests', function () { | |
var service; | |
beforeEach(function () { | |
module('test'); | |
inject(function ($injector) { | |
service = $injector.get('userService'); | |
}); | |
}); | |
describe('Initialization', function () { | |
it('Should load the usersJson from the service', function () { | |
expect(service.getUsers.length).toBeGreaterThan(0); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment