AngularJS Unit Testing with Karma & Jasmine
โก Akฤฑllฤฑ รzet
AngularJS Unit Testing with Karma and Jasmine verifies controllers, directives, and services in isolation. Karma runs specifications inside real browsers, Jasmine supplies the assertion syntax, and angular-mocks injects dependencies without a live server.

One of the most brilliant features of AngularJS is the Test yapmak Bu yรถn. Geliลtiriciler Google AngularJS'i geliลtirirken, test etmeyi gรถz รถnรผnde bulundurdular ve tรผm AngularJS รงerรงevesinin test edilebilir olmasฤฑnฤฑ saฤladฤฑlar.
In AngularJS, testing is normally carried out using Karma (framework). AngularJS testing can be carried out without Karma, but the Karma framework has such a brilliant functionality for testing AngularJS code, that it makes sense to use this framework.
- AngularJS'de ลunlarฤฑ gerรงekleลtirebiliriz: Birim Testi denetleyiciler ve yรถnergeler iรงin ayrฤฑ ayrฤฑ.
- Biz de performans gรถsterebiliriz end to end testing of AngularJS, which is testing from a user perspective.
โ ๏ธ Sรผrรผm notu: AngularJS (version 1.x) reached official end of life on 31 December 2021, and Protractor was retired in August 2023. The workflow on this page remains valid for maintaining existing AngularJS 1.x applications. New projects should use modern Angular with a currently supported runner.
Karma รงerรงevesinin tanฤฑtฤฑmฤฑ ve kurulumu
Karma bir otomasyon aracฤฑnฤฑ test etme created by the AngularJS team at Google. Karma'yฤฑ kullanmanฤฑn ilk adฤฑmฤฑ Karma'yฤฑ yรผklemektir. Karma, npm (modรผllerin yerel bir makineye kolay kurulumu iรงin kullanฤฑlan bir paket yรถneticisi) aracฤฑlฤฑฤฤฑyla kurulur.
Karma'nฤฑn Kurulumu
Karma'nฤฑn npm aracฤฑlฤฑฤฤฑyla kurulumu iki adฤฑmlฤฑ bir iลlemle gerรงekleลtirilir.
) 1 Adฤฑm Aลaฤฤฑdaki satฤฑrฤฑ komut satฤฑrฤฑndan yรผrรผtรผn
npm install karma karma-chrome-launcher karma-jasmine --save-dev
burada,
- npm is the command line utility for the node package manager used for installing custom modules on any machine. It ships with node.js.
- Kurulum parametresi, npm komut satฤฑrฤฑ yardฤฑmcฤฑ programฤฑna kurulumun gerekli olduฤunu bildirir.
- Karma ile รงalฤฑลmak iรงin gereken komut satฤฑrฤฑnda belirtilen 3 kitaplฤฑk vardฤฑr.
- karma, test amacฤฑyla kullanฤฑlacak รงekirdek kรผtรผphanedir.
- karma-chrome-launcher, karma komutlarฤฑnฤฑn Chrome tarayฤฑcฤฑ tarafฤฑndan tanฤฑnmasฤฑnฤฑ saฤlayan ayrฤฑ bir kitaplฤฑktฤฑr.
- karma-yasemin โ Bu, Karma iรงin baฤฤฑmlฤฑ bir รงerรงeve olan yasemin yรผkler.
) 2 Adฤฑm Bir sonraki adฤฑm karma komut satฤฑrฤฑ yardฤฑmcฤฑ programฤฑnฤฑ yรผklemektir. Bu, karma satฤฑrฤฑ komutlarฤฑnฤฑ yรผrรผtmek iรงin gereklidir. Karma hattฤฑ yardฤฑmcฤฑ programฤฑ, karma ortamฤฑnฤฑ test amacฤฑyla baลlatmak iรงin kullanฤฑlacaktฤฑr.
Komut satฤฑrฤฑ yardฤฑmcฤฑ programฤฑnฤฑ yรผklemek iรงin komut satฤฑrฤฑndan aลaฤฤฑdaki satฤฑrฤฑ รงalฤฑลtฤฑrฤฑn
npm install -g karma-cli
- karma-cli is used to install the command line interface for karma which will be used to write the karma commands in the command line interface. The -g flag installs it globally so that the karma command is available from any folder.
Karma รงerรงevesinin yapฤฑlandฤฑrฤฑlmasฤฑ
Bir sonraki adฤฑm, komut aracฤฑlฤฑฤฤฑyla yapฤฑlabilecek karmayฤฑ yapฤฑlandฤฑrmaktฤฑr.
karma init
Yukarฤฑdaki adฤฑm yรผrรผtรผldรผkten sonra karma, bir karma.conf.js dosyasฤฑ oluลturacaktฤฑr. Dosya muhtemelen aลaฤฤฑda gรถsterilen kod parรงasฤฑna benzeyecektir
files: [ 'node_modules/angular/angular.js', 'node_modules/angular-mocks/angular-mocks.js', 'lib/app.js', 'tests/*.js' ]
Yukarฤฑdaki yapฤฑlandฤฑrma dosyalarฤฑ karma รงalฤฑลma zamanฤฑ motoruna ลu ลeyleri sรถyler:
- angular.js โ This tells karma that your application depends on the core modules in AngularJS.
- angular-mocks.js โ This tells karma to use the Unit Testing functionality for AngularJS from the angular-mocks.js file.
- Ana uygulama veya iล mantฤฑฤฤฑ dosyalarฤฑnฤฑn tรผmรผ uygulamanฤฑzฤฑn lib klasรถrรผnde mevcuttur.
- Testler klasรถrรผ tรผm birim testlerini iรงerecektir.
๐ก ฤฐpucu: Order matters inside the files array. angular.js must load before angular-mocks.js, and both must load before your application code, otherwise the injector is not available when the specifications run.
Karmanฤฑn รงalฤฑลฤฑp รงalฤฑลmadฤฑฤฤฑnฤฑ kontrol etmek iรงin Sample.js adฤฑnda bir dosya oluลturun, aลaฤฤฑdaki kodu koyun ve test dizinine yerleลtirin.
describe('Sample test', function() { it('Condition is true', function() { expect('AngularJS').toBe('AngularJS'); }); });
Yukarฤฑdaki kodun ลu yรถnleri vardฤฑr
- Aรงฤฑklama fonksiyonu testin aรงฤฑklamasฤฑnฤฑ vermek iรงin kullanฤฑlฤฑr. Bizim durumumuzda testimize 'รrnek test' aรงฤฑklamasฤฑnฤฑ veriyoruz.
- Teste isim vermek iรงin 'it' fonksiyonu kullanฤฑlฤฑr. Bizim durumumuzda testimizin adฤฑnฤฑ 'Koลul doฤrudur' olarak veriyoruz. Testin isminin anlamlฤฑ olmasฤฑ gerekmektedir.
- 'Beklemek' ve 'olmak' anahtar kelimelerinin birleลimi, test sonucunun beklenen ve gerรงek deฤerinin ne olduฤunu belirtir. Gerรงek ve beklenen deฤer aynฤฑ ise test baลarฤฑlฤฑ olacak, aksi halde baลarฤฑsฤฑz olacaktฤฑr.
Komut isteminde aลaฤฤฑdaki satฤฑrฤฑ รงalฤฑลtฤฑrdฤฑฤฤฑnฤฑzda yukarฤฑdaki test dosyasฤฑ รงalฤฑลtฤฑrฤฑlacaktฤฑr
karma start
Aลaฤฤฑdaki รงฤฑktฤฑ IDE'den alฤฑnmฤฑลtฤฑr Webstorm yukarฤฑdaki adฤฑmlarฤฑn gerรงekleลtirildiฤi yer.
- รฤฑktฤฑ Karma Explorer'da gelir Webstorm. Bu pencere karma รงerรงevesinde tanฤฑmlanan tรผm testlerin yรผrรผtรผlmesini gรถsterir.
- Burada yรผrรผtรผlen testin aรงฤฑklamasฤฑnฤฑn โรrnek testโ olarak gรถsterildiฤini gรถrebilirsiniz.
- Daha sonra โKoลul doฤrudurโ adฤฑndaki testin kendisinin yรผrรผtรผldรผฤรผnรผ gรถrebilirsiniz.
- Tรผm testlerin yanฤฑnda, tรผm testlerin geรงtiฤini simgeleyen yeลil "Tamam" simgesinin bulunduฤunu unutmayฤฑn.
What is Jasmine in AngularJS Unit Testing?
Karma decides where tests run, while Jasmine decides how they are written. Jasmine is a behaviour driven specification framework that supplies the vocabulary used in every example on this page, which is why the karma-jasmine adapter is installed alongside the runner.
Jasmine contributes four building blocks:
- describe(): Groups related specifications into a suite and accepts a readable description of the unit under test.
- it(): Declares a single specification. The name should state the behaviour being verified rather than the method being called.
- expect() with matchers: Compares an actual value against an expected one. Common matchers include toBe, toEqual, toContain, and toBeDefined.
- beforeEach() and afterEach(): Run setup and teardown before and after every specification, which keeps each test independent.
Jasmine also provides spies. A spy replaces a real function with a recorded stand in, so a controller can be tested without calling a live HTTP endpoint. Because Jasmine needs no DOM and no assertion library of its own, the combination of Karma and Jasmine remains the lightest way to run AngularJS JavaScript unit tests.
AngularJS Denetleyicilerini Test Etme
Karma test รงerรงevesi aynฤฑ zamanda Denetleyicileri uรงtan uca test etme iลlevine de sahiptir. Buna Denetleyiciler iรงinde kullanฤฑlan $scope nesnesinin test edilmesi de dahildir.
Bunu nasฤฑl baลarabileceฤimize dair bir รถrneฤe bakalฤฑm.
รrneฤimizde,
รncelikle bir kontrolรถr tanฤฑmlamamฤฑz gerekiyor. Bu kontrolรถr aลaฤฤฑda belirtilen adฤฑmlarฤฑ gerรงekleลtirecektir
- Bir kimlik deฤiลkeni oluลturun ve ona 5 deฤerini atayฤฑn.
- Kimlik deฤiลkenini $scope nesnesine atayฤฑn.
Testimiz bu denetleyicinin varlฤฑฤฤฑnฤฑ test edecek ve ayrฤฑca $scope nesnesinin kimlik deฤiลkeninin 5'e ayarlanฤฑp ayarlanmadฤฑฤฤฑnฤฑ test edecektir.
รncelikle aลaฤฤฑdaki รถn koลulun mevcut olduฤundan emin olmamฤฑz gerekiyor
Install the angular-mocks library via npm. This can be done by executing the below line in the command prompt
npm install angular-mocks --save-dev
Sonraki adฤฑm, teste doฤru dosyalarฤฑn dahil edildiฤinden emin olmak iรงin karma.conf.js dosyasฤฑnฤฑ deฤiลtirmektir. Aลaฤฤฑdaki bรถlรผm sadece karma.conf.js dosyasฤฑnฤฑn deฤiลtirilmesi gereken dosya kฤฑsmฤฑnฤฑ gรถstermektedir
files: ['lib/angular.js', 'lib/angular-mocks.js', 'lib/index.js', 'test/*.js']
- 'files' parametresi temel olarak Karma'ya testlerin yรผrรผtรผlmesi iรงin gerekli olan tรผm dosyalarฤฑ bildirir.
- The angular.js and angular-mocks.js file are required to run AngularJS unit tests
- ฤฐndex.js dosyasฤฑ denetleyiciye ait kodumuzu iรงerecektir
- Test klasรถrรผ tรผm AngularJS testlerimizi iรงerecektir
Below is our AngularJS code which will be stored as a file Index.js in the test folder of our application.
Aลaฤฤฑdaki kod sadece ลu ลeyleri yapar
- Bir oluลturma AngularJS modรผlรผ sampleApp denir
- AngularJSController adฤฑnda bir denetleyici oluลturun
- ID adฤฑnda bir deฤiลken oluลturun, ona 5 deฤerini verin ve onu $scope nesnesine atayฤฑn
var sampleApp = angular.module('sampleApp', []); sampleApp.controller('AngularJSController', function($scope) { $scope.ID = 5; });
Yukarฤฑdaki kod baลarฤฑyla yรผrรผtรผldรผฤรผnde, bir sonraki adฤฑm bir oluลturmak olacaktฤฑr. Test Durumu Kodun doฤru ลekilde yazฤฑldฤฑฤฤฑndan ve yรผrรผtรผldรผฤรผnden emin olmak iรงin.
Testimizin kodu aลaฤฤฑdaki gibi olacaktฤฑr.
Kod, test klasรถrรผne yerleลtirilecek ControllerTest.js adlฤฑ ayrฤฑ bir dosyada olacak. Aลaฤฤฑdaki kod yalnฤฑzca ลu temel ลeyleri yapar
- beforeEach function โ This function is used to load our AngularJS module called โsampleAppโ before the test run. Note that this is the name of the module in an index.js file.
- The $controller object is created as a mockup object for the controller โAngularJSControllerโ which is defined in our index.js file. In any sort of Unit Testing, a mock object represents a dummy object which will actually be used for the testing. This mock object will actually simulate the behavior of our controller.
- beforeEach(inject(function(_$controller_)) โ Bu, gerรงek denetleyici gibi davranmasฤฑ iรงin testimize sahte nesneyi enjekte etmek iรงin kullanฤฑlฤฑr.
- var $kapsam = {}; Bu, $scope nesnesi iรงin oluลturulan sahte bir nesnedir.
- var controller = $controller(โAngularJSControllerโ, { $scope: $scope }); โ Here we are checking for the existence of a controller named โAngularJSControllerโ. In here we are also assigning all variables from our $scope object in our controller in the Index.js file to the $scope object in our test file
- Son olarak $scope.ID deฤerini 5 ile karลฤฑlaลtฤฑrฤฑyoruz.
describe('AngularJSController', function() { beforeEach(module('sampleApp')); var $controller; beforeEach(inject(function(_$controller_){ $controller = _$controller_; })); describe('$scope.ID', function() { it('Check the scope object', function() { var $scope = {}; var controller = $controller('AngularJSController', { $scope: $scope }); expect($scope.ID).toEqual(5); }); }); });
Yukarฤฑdaki test karma tarayฤฑcฤฑsฤฑnda รงalฤฑลacak ve รถnceki konuda gรถsterilenle aynฤฑ baลarฤฑlฤฑ sonucu verecektir.
AngularJS Direktiflerini Test Etme
Karma test รงerรงevesi, รถzel yรถnergeleri test etme iลlevine de sahiptir. Bu, ลablonu da iรงerir.URLรzel yรถnergeler iรงerisinde kullanฤฑlan 'ler.
Bunu nasฤฑl baลarabileceฤimize dair bir รถrneฤe bakalฤฑm.
รrneฤimizde, รถncelikle aลaฤฤฑdaki iลlemleri yapan รถzel bir yรถnerge tanฤฑmlayacaฤฤฑz
- sampleApp adฤฑnda bir AngularJS modรผlรผ oluลturun
- Create a custom directive with the name โ guru99
- "Bu AngularJS Testidir" metnini gรถrรผntรผleyen baลlฤฑk etiketine sahip bir ลablon dรถndรผren bir iลlev oluลturun.
var sampleApp = angular.module('sampleApp', []); sampleApp.directive('guru99', function () { return { restrict: 'E', replace: true, template: '<h1>This is AngularJS Testing</h1>' }; });
Yukarฤฑdaki kod baลarฤฑyla รงalฤฑลtฤฑrฤฑldฤฑktan sonraki adฤฑm, kodun dรผzgรผn bir ลekilde yazฤฑldฤฑฤฤฑndan ve yรผrรผtรผldรผฤรผnden emin olmak iรงin bir test senaryosu oluลturmak olacaktฤฑr. Testimizin kodu aลaฤฤฑda gรถsterildiฤi gibi olacaktฤฑr.
Kod, test klasรถrรผne yerleลtirilecek olan DirectionTest.js adlฤฑ ayrฤฑ bir dosyada olacaktฤฑr. Aลaฤฤฑdaki kod yalnฤฑzca ลu temel ลeyleri yapar
- beforeEach function โ This function is used to load our AngularJS module called โsampleAppโ before the test run.
- The $compile service is used to compile the directive. This service is mandatory and needs to be declared so that AngularJS can use it to compile our custom directive.
- The $rootScope is the primary scope of any AngularJS application. We have seen the $scope object of the controller in earlier chapters. Well, the $scope object is the child object of the $rootScope object. The reason this is declared here is because we are making a change to an actual HTML tag in the DOM via our custom directive. Hence, we need to use the $rootScope service which actually listens or knows when any change happens from within an HTML document.
- var element = $compile(โ<guru99></guru99>โ)($rootScope) โ This is used to check whether our directive gets injected as it should. The directive is registered with the camel case name guru99, so AngularJS matches the lowercase element <guru99> in the markup. Hence this statement is used to make that check.
- expect(element.html()).toContain(โThis is AngularJS Testingโ) โ This is used to instruct the expect function that it should find the element(in our case the h1 tag) to contain the innerHTML text of โThis is AngularJS Testingโ.
describe('Unit testing directives', function() { var $compile, $rootScope; beforeEach(module('sampleApp')); beforeEach(inject(function(_$compile_, _$rootScope_){ $compile = _$compile_; $rootScope = _$rootScope_; })); it('Check the directive', function() { // Compile a piece of HTML containing the directive var element = $compile("<guru99></guru99>")($rootScope); $rootScope.$digest(); expect(element.html()).toContain("This is AngularJS Testing"); }); });
Yukarฤฑdaki test karma tarayฤฑcฤฑsฤฑnda รงalฤฑลacak ve รถnceki konuda gรถsterilenle aynฤฑ baลarฤฑlฤฑ sonucu verecektir.
End to End Testing AngularJS applications
Karma test รงerรงevesi, Pro adฤฑ verilen bir รงerรงeveyle birlikte kullanฤฑlฤฑr.tracTor, bir web uygulamasฤฑnฤฑ uรงtan uca test etme iลlevine sahiptir.
Yani bu sadece direktiflerin ve denetleyicilerin test edilmesi deฤil aynฤฑ zamanda bir HTML sayfasฤฑnda gรถrรผnebilecek diฤer her ลeyin test edilmesidir.
Bunu nasฤฑl baลarabileceฤimize dair bir รถrneฤe bakalฤฑm.
Aลaฤฤฑdaki รถrneฤimizde ng-repeat direktifini kullanarak veri tablosu oluลturan bir AngularJS uygulamamฤฑz olacak.
- รncelikle โรถฤreticiโ adฤฑ verilen bir deฤiลken oluลturuyoruz ve ona tek adฤฑmda bazฤฑ anahtar/deฤer รงiftlerini atadฤฑk. Tablo gรถrรผntรผlenirken her anahtar/deฤer รงifti veri olarak kullanฤฑlacaktฤฑr. รฤretici deฤiลken daha sonra kapsam nesnesine atanฤฑr, bรถylece ona gรถrรผnรผmรผmรผzden eriลilebilir.
- Tablodaki her veri satฤฑrฤฑ iรงin ng-repeat direktifini kullanฤฑyoruz. Bu yรถnerge, ptutor deฤiลkenini kullanarak eฤitim kapsamฤฑ nesnesindeki her anahtar/deฤer รงiftinden geรงer.
- Son olarak ลunu kullanฤฑyoruz: anahtar deฤer รงiftleriyle birlikte etiketleyin (ptutor.Name ve ptutor.Description) tablo verilerini gรถrรผntรผlemek iรงin.
<table> <tr ng-repeat="ptutor in tutorial"> <td>{{ ptutor.Name }}</td> <td>{{ ptutor.Description }}</td> </tr> </table> </div> <script type="text/javascript"> var app = angular.module('DemoApp', []); app.controller('DemoController', function($scope) { $scope.tutorial = [ {Name: "Controllers", Description: "Controllers in action"}, {Name: "Models", Description: "Models and binding data"}, {Name: "Directives", Description: "Flexibility of Directives"} ]; });
Yukarฤฑdaki kod baลarฤฑyla รงalฤฑลtฤฑrฤฑldฤฑktan sonraki adฤฑm, kodun dรผzgรผn bir ลekilde yazฤฑldฤฑฤฤฑndan ve yรผrรผtรผldรผฤรผnden emin olmak iรงin bir test senaryosu oluลturmak olacaktฤฑr. Testimizin kodu aลaฤฤฑda gรถsterildiฤi gibi olacaktฤฑr.
Testimiz aslฤฑnda ng-repeat direktifini test edecek ve yukarฤฑdaki รถrnekte olmasฤฑ gerektiฤi gibi 3 satฤฑrlฤฑk veri iรงerdiฤinden emin olacak.
รncelikle aลaฤฤฑdaki รถn koลulun mevcut olduฤundan emin olmamฤฑz gerekiyor
profesyoneli yรผkleyintracnpm aracฤฑlฤฑฤฤฑyla Tor kรผtรผphanesini ekleyebilirsiniz. Bunu, komut isteminde aลaฤฤฑdaki satฤฑrฤฑ รงalฤฑลtฤฑrarak yapabilirsiniz.
npm install -g protractor
Testimizin kodu aลaฤฤฑdaki gibi olacaktฤฑr.
Kod, test klasรถrรผne yerleลtirilecek olan CompleteTest.js adlฤฑ ayrฤฑ bir dosyada olacak. Aลaฤฤฑdaki kod yalnฤฑzca ลu temel ลeyleri yapar
- Tarayฤฑcฤฑ iลlevi profesyonel tarafฤฑndan saฤlanmaktadฤฑr.tracTor kรผtรผphanesini kullanฤฑr ve yukarฤฑda gรถsterilen kodla birlikte AngularJS uygulamamฤฑzฤฑn sitemizde รงalฤฑลtฤฑฤฤฑnฤฑ varsayar. URL โ http://localhost:8080/Guru99 /
- var list = element.all(by.repeater(โptutor in tutorialโ)); -This line of code is actually fetching the ng-repeat directive which is populated by the code โptutor in tutorialโ. The element and by.repeater are special keywords provided by the protracng-repeat yรถnergesinin ayrฤฑntฤฑlarฤฑnฤฑ almamฤฑzฤฑ saฤlayan bir Tor kรผtรผphanesi.
- beklenti(list.count()).toEqual(3); โ Son olarak, ng-repeat direktifinin bir sonucu olarak tablomuzda gerรงekten 3 รถฤenin doldurulduฤunu gรถrmek iรงin wait fonksiyonunu kullanฤฑyoruz.
describe('Unit testing end to end', function() { beforeEach(function() { browser.get('http://localhost:8080/Guru99/'); }); it('Check the ng directive', function() { var list = element.all(by.repeater('ptutor in tutorial')); expect(list.count()).toEqual(3); }); });
Yukarฤฑdaki test karma tarayฤฑcฤฑsฤฑnda รงalฤฑลacak ve รถnceki konuda gรถsterilenle aynฤฑ baลarฤฑlฤฑ sonucu verecektir.
Karma vs Jasmine vs Protractor: Key Differences
The three tools used across this page are often confused because they appear in the same command line. Each one occupies a different layer of the testing stack, as the table below makes clear.
| Parametre | Karma | Yasemin | baลฤฑnatractor |
| Kategoriler | Test runner | Specification framework | End to end automation framework |
| Asฤฑl iล | Launches browsers and reports results | Provides describe, it, and expect | Drives a live application in a real browser |
| Test seviyesi | birim ve bรผtรผnleลme | Unit and integration | Baลtan sona |
| Needs a running server | Yok hayฤฑr | Yok hayฤฑr | Evet |
| yapฤฑlandฤฑrma dosyasฤฑ | karma.conf.js | None, it runs inside a runner | iรงintractor.conf.js |
| Mevcut durum | Deprecated, maintenance only | Aktif bakฤฑmlฤฑ | Retired in August 2023 |
In short, Jasmine writes the test, Karma executes it, and Protractor extends the same Jasmine syntax to a fully rendered page.
Best Practices for AngularJS Unit Testing
A small set of habits keeps an AngularJS suite fast and trustworthy as the application grows.
- Test one unit at a time. Load only the module under test inside beforeEach, and mock every collaborator so a failure points at a single file.
- Never call a real backend. Use the $httpBackend service from angular-mocks to return canned responses. Tests then run offline and produce identical results on every machine.
- Keep specification names behavioural. A name such as โreturns 5 when the controller initialisesโ reads better in a report than โtest1โ.
- Always flush the digest cycle. Call $rootScope.$digest() after changing scope data, otherwise bindings and watchers never update and assertions fail for the wrong reason.
- Measure coverage, but judge it carefully. Add karma-coverage to see untested branches. High coverage with weak assertions still hides defects.
- Run the suite in continuous integration. Use a headless Chrome launcher so the same specifications execute on every commit rather than only on a developer machine.
Applying these rules turns the examples above from isolated demonstrations into a regression safety net for a legacy AngularJS codebase. For the wider picture, see the AngularJS tutorial serisi.

