{"id":595,"date":"2016-07-12T10:09:00","date_gmt":"2016-07-12T10:09:00","guid":{"rendered":"https:\/\/staging.infragistics.com\/blogs\/?p=595"},"modified":"2025-02-25T14:44:03","modified_gmt":"2025-02-25T14:44:03","slug":"jasmine-and-karma-unit-tests","status":"publish","type":"post","link":"https:\/\/www.infragistics.com\/blogs\/jasmine-and-karma-unit-tests","title":{"rendered":"Using Jasmine &amp; Karma to Write and Run Unit Tests for AngularJS Apps"},"content":{"rendered":"\n<p>Note: Although we say this post will show you how to use Visual Studio to write AngularJS applications and unit tests, you can use these methods to configure test environments for <i>any<\/i> IDE. \u00a0<\/p>\n\n\n\n<p>In this post we will cover the following topics:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Setting up the development environment<\/li>\n\n\n\n<li>Setting up the test environment for jasmine<\/li>\n\n\n\n<li>Setting up the karma test runner environment<\/li>\n\n\n\n<li>Writing the unit test for filter, controller, and service<\/li>\n<\/ul>\n\n\n\n<p>We will use <b>npm<\/b> to install dependencies and Visual Studio to write code, and we\u2019ll run tests using karma from the command prompt. At the end of the post, we should have tests running as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/4503.pic1.png\" alt=\" At the end of the post, we should have tests running as shown in the image\" title=\"At the end of the post, we should have tests running as shown in the image\"\/><\/figure>\n\n\n\n<p>So let\u2019s get started!<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-1\">Step 1 <\/h2>\n\n\n\n<p>Create an ASP.NET Web Application project in Visual Studio by choosing the Empty template project type.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angukarjsunittest\/1234.pic2.png\" alt=\"New ASP.NET Project - AngularTestDemp\" title=\"New ASP.NET Project - AngularTestDemp\"\/><\/figure>\n\n\n\n<p>Even though I am creating an AngularJS project in Visual Studio, you can create project using any IDE of your choice. The only thing you need to keep in mind is that all commands we will run here should be executed inside the root folder of the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-2\">Step 2 <\/h2>\n\n\n\n<p>Once the project is created, launch the command prompt as an admin and change the directory to the root folder of created project folder. In the case of Visual Studio, change the directory to the project folder, not the solution folder.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/3426.pic2.png\" alt=\" Once the project is created, launch the command prompt as an admin and change the directory to the root folder of created project folder\" title=\"Once the project is created, launch the command prompt as an admin and change the directory to the root folder of created project folder\"\/><\/figure>\n\n\n\n<p>For example, the folder structure I am using is as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>AngularJSUnitTestDemo : Solution Folder<\/li>\n\n\n\n<li>AngularJSUnitTestDemo : Root folder of project. So, we navigated here.<\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-3\">Step 3<\/h2>\n\n\n\n<p>We need to make sure that NodeJS is installed on the machine. If it is not installed, download and install it from <a href=\"https:\/\/nodejs.org\/en\/\" rel=\"noopener\">https:\/\/nodejs.org\/en\/<\/a>. We can verify whether NodeJS is installed or not by running the following command:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><b>node &#8211;version\u00a0 <\/b><\/li>\n<\/ul>\n\n\n\n<p>If we get <b>NodeJS version<\/b> as output, then NodeJS is installed on the machine.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/6574.pic3.png\" alt=\" we get NodeJS version as output, then NodeJS is installed\" title=\"we get NodeJS version as output, then NodeJS is installed\"\/><\/figure>\n\n\n\n<p>In this step, we installed and verified NodeJS.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-4\">Step 4 <\/h2>\n\n\n\n<p>Next, let\u2019s install AngularJS to the project. There are various ways to do so (NuGet package, Bower etc.), however, I am choosing NPM to install AngularJS in the project. To install, run the npm command as shown below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\u00a0<b>npm install angular &#8211;save<\/b><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/8233.pic4.png\" alt=\" this step, we have installed AngularJS to the project\" title=\"this step, we have installed AngularJS to the project\"\/><\/figure>\n\n\n\n<p>In this step, we have installed AngularJS to the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-5\">Step 5 <\/h2>\n\n\n\n<p>Now we are going to use Karma test runner to run tests.&nbsp; Learn more about Karma here: <a href=\"https:\/\/karma-runner.github.io\/1.0\/index.html\" rel=\"noopener\">https:\/\/karma-runner.github.io\/1.0\/index.html<\/a> Created by the Angular team, Karma is a spec-based test runner. To install Karma, run the command as shown below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\u00a0<b>npm install -g karma &#8211;save-dev<\/b><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/3438.pic5.png\" alt=\" In this step, we have installed Karma in the project.\" title=\"In this step, we have installed Karma in the project.\"\/><\/figure>\n\n\n\n<p>In this step, we have installed Karma in the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-6\">Step 6 <\/h2>\n\n\n\n<p>We are going to use Jasmine, behavior driven JavaScript Test framework to write Unit Tests. Learn more about Jasmine here:&nbsp; <a href=\"http:\/\/jasmine.github.io\" rel=\"noopener\">http:\/\/jasmine.github.io<\/a><\/p>\n\n\n\n<p>We will install Jasmine Core and Jasmine Karma. To install them run the command as shown below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><b>npm install karma-jasmine jasmine-core &#8211;save-dev<\/b><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/2055.pic6.png\" alt=\" In this step, we have installed the jasmine core and the jasmine karma plugin in the project.\" title=\"In this step, we have installed the jasmine core and the jasmine karma plugin in the project.\"\/><\/figure>\n\n\n\n<p>&nbsp;In this step, we have installed the jasmine core and the jasmine karma plugin in the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-7\">Step 7<\/h2>\n\n\n\n<p>We will use the ngMock module to mock up AngularJS services, modules, controllers, filters and more. To use ngMock, we need to install the <b>angular-mocks<\/b> library in the project. To do so, run the command as shown below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><b>npm install angular-mocks &#8211;save-dev<\/b><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/2870.pic7.png\" alt=\" In this step, we have installed angular-mocks library in the project.\" title=\"In this step, we have installed angular-mocks library in the project.\"\/><\/figure>\n\n\n\n<p>&nbsp;In this step, we have installed angular-mocks library in the project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-8\">Step 8<\/h2>\n\n\n\n<p>Karma allows us to run tests in multiple browsers. To do so, we need to install different browser plugins. In this example, I\u2019d like to run a test in Chrome, so I\u2019ll go ahead and install a Chrome browser plugin as follows:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><b>npm install karma-chrome-launcher &#8211;save-dev<\/b><\/li>\n<\/ul>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/4024.pic8.png\" alt=\" we have installed the Chrome browser karma launcher\" title=\"we have installed the Chrome browser karma launcher\"\/><\/figure>\n\n\n\n<p>In this step, we have installed the Chrome browser karma launcher. If you wish, you can install other browser launchers too.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-9\">Step 9<\/h2>\n\n\n\n<p>We can have any folder structure for the project adhering to our business requirements. However, for the purpose of this post, I am going to keep it simple. I will create two folders: app and tests. The app folder will keep all Angular scripts files and the tests folder to keep all the tests. To create these folders, &nbsp;run the commands as shown below:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><b>md app<\/b><\/li>\n\n\n\n<li><b>md tests<\/b><\/li>\n<\/ul>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-10\">Step 10 <\/h2>\n\n\n\n<p>This step is only required if you are working in Visual Studio, otherwise you can skip this step. We are going to add all newly installed files and newly created folder in the project. Go back to Visual Studio.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angukarjsunittest\/7103.pic11.png\" alt=\" In this step we have included all of our newly created files and folders in Visual Studio\" title=\"In this step we have included all of our newly created files and folders in Visual Studio\"\/><\/figure>\n\n\n\n<p>In this step we have included all of our newly created files and folders in Visual Studio project.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-11\">Step 11<\/h2>\n\n\n\n<p>In this step, we are going to add new files to the project:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li><b>CalculatorApp.js<\/b> to write AngularJS code. Add this file in app folder.<\/li>\n\n\n\n<li><b>CalculatorAppTest.js<\/b> to write unit tests for controller, filters, services written in CalculatorApp.js. Add this file in tests folder.<\/li>\n\n\n\n<li><b>SpecRunner.html<\/b> to display test results in browser using jasmine<\/li>\n\n\n\n<li><b>Index.html<\/b>, html page of the application.<\/li>\n<\/ul>\n\n\n\n<p>To add files in Visual Studio,<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Right click on the project\/ app folder and add a file called <b>CalculatorApp.js<\/b><\/li>\n\n\n\n<li>Right click on the project\/tests folder and add a file called <b>CalculatorAppTest.js<\/b><\/li>\n\n\n\n<li>Right click on the project and add an HTML file called <b>SpecRunner.html<\/b><\/li>\n\n\n\n<li>Right click on the project and add an HTML file called <b>index.html<\/b><\/li>\n<\/ul>\n\n\n\n<p>In this step, we have added new files to write code, unit test and display test results.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-12\">Step 12<\/h2>\n\n\n\n<p>In this step, we will setup SpecRunner.html. This will render test results in the browser. So, open SpecRunner.html and add the following references.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">Jasmine Test Results\n    &lt;meta charset=\"utf-8\" \/>\n    &lt;link href=\"node_modules\/jasmine-core\/lib\/jasmine-core\/jasmine.css\" rel=\"stylesheet\" \/>\n    &lt;script src=\"node_modules\/jasmine-core\/lib\/jasmine-core\/jasmine.js\">&lt;\/script>\n    &lt;script src=\"node_modules\/jasmine-core\/lib\/jasmine-core\/jasmine-html.js\">&lt;\/script>\n    &lt;script src=\"node_modules\/jasmine-core\/lib\/jasmine-core\/boot.js\">&lt;\/script>\n\n    &lt;script src=\"node_modules\/angular\/angular.js\">&lt;\/script>\n    &lt;script src=\"node_modules\/angular-mocks\/angular-mocks.js\">&lt;\/script>\n\n    &lt;script src=\"app\/CalculatorApp.js\">\n    &lt;script src=\"tests\/CalculatorAppTest.js\">&lt;\/script><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-13-writing-tests-for-angularjs-filter\">Step 13 &#8211; Writing Tests for AngularJS filter<\/h2>\n\n\n\n<p>Finally, we have reached to step in which we will write some tests! Let\u2019s start by writing tests for the AngularJS filter. Add following test to <b>CalculatorAppTest.js<\/b>.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">describe('Calculator App Tests', function () {\n\n    beforeEach(module('MyApp'));\n\n    describe('reversestringfiltertest', function () {\n\n        var reverse;\n        beforeEach(inject(function ($filter) { \/\/initialize filter\n            reverse = $filter('reverse', {});\n        }));\n\n        it('Should reverse a string', function () { \n            expect(reverse('india')).toBe('aidni'); \/\/pass test\n            expect(reverse('don')).toBe('don'); \/\/fail test\n        });\n    });\n});<\/pre>\n\n\n\n<p>In the above code snippet, we are creating a proxy of the module and filter using ng-mock. We have written tests for the filter name \u2018reverse\u2019 from module \u2018MyApp\u2019 and we are injecting the filter using the $filter service of ng-mock.<\/p>\n\n\n\n<p>At this point, if we go ahead and run the SpecRunner.html, we will get a failed test result because we have not created the AngularJS filter or the \u2018MyApp\u2019 module.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angukarjsunittest\/0257.pic12.png\" alt=\" At this point, if we go ahead and run the SpecRunner.html, we will get a failed test result because we have not created the AngularJS filter or the \u2018MyApp\u2019 module\" title=\"At this point, if we go ahead and run the SpecRunner.html, we will get a failed test result because we have not created the AngularJS filter or the \u2018MyApp\u2019 module\"\/><\/figure>\n\n\n\n<p>So now let us go ahead and create an AngularJS Module \u2018MyApp\u2019 with filter \u2018reverse\u2019. We will create these in the <b>App\/CalculatorApp.js<\/b><\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">var MyApp = angular.module(\"MyApp\", []);\n\nMyApp.filter('reverse', [function () {\n    return function (string) {\n        return string.split('').reverse().join('');\n    }\n}]);<\/pre>\n\n\n\n<p>Now go back and run once again, run SpecRunner.html. We will find, once again test is failed. As it is showing in test failure message that \u2013 Expected \u2018nod\u2019 to be \u2018don\u2019<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angukarjsunittest\/4035.pic13.png\" alt=\" We will find, once again test is failed. As it is showing in test failure message that \u2013 Expected \u2018nod\u2019 to be \u2018don\u2019\" title=\"We will find, once again test is failed. As it is showing in test failure message that \u2013 Expected \u2018nod\u2019 to be \u2018don\u2019\"\/><\/figure>\n\n\n\n<p>If you remember, we deliberately wrote a failed test. So now let\u2019s go ahead and fix the test in CalculatorAppTest.js<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">describe('Calculator App Tests', function () {\n\n    beforeEach(module('MyApp'));\n\n    describe('reversestringfiltertest', function () {\n\n        var reverse;\n        beforeEach(inject(function ($filter) { \/\/initialize filter\n            reverse = $filter('reverse', {});\n        }));\n\n        it('Should reverse a string', function () { \n            expect(reverse('india')).toBe('aidni');\n            expect(reverse('don')).toBe('nod'); \n        });\n    });\n});<\/pre>\n\n\n\n<p>When we run the test in SpecRunner.html, we\u2019ll find all tests are passed as shown in the image below.<\/p>\n\n\n\n<p>In this step, we wrote a test for AngularJS filter and ran that using Jasmine SpecRunner.html.<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">Problems in running test using SpecRunner.html <\/h3>\n\n\n\n<p>You may have noticed the only problem in the approach above is that each time we change the test code or source code, we need to go back and either load SpecRunner.html again or refresh it manually to see the updated test result. In real project development, this could be a pain. We need a mechanism in which whenever the code changes, tests should be executed automatically. To do this, we have test runner. We have already installed the <b>Karma<\/b> test runner to automatically run tests whenever code changes, so now let\u2019s configure it to do that.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-14\">Step 14<\/h2>\n\n\n\n<p>To configure Karma, we need to run command Karma init.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">karma init<\/pre>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/3022.pic9.png\" alt=\" configure Karma, we need to run command Karma init\" title=\"configure Karma, we need to run command Karma init\"\/><\/figure>\n\n\n\n<p>You will be prompted with many questions to answer, use the following answers as displayed below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/0726.pic10.png\" alt=\" You will be prompted with many questions to answer, use the following answers as displayed\" title=\"You will be prompted with many questions to answer, use the following answers as displayed\"\/><\/figure>\n\n\n\n<p>Karma.cnf.js file has been created after answering those questions. Next, let us open Visual Studio and include the newly created file <b>Karma.conf.js<\/b> in project.&nbsp; Open Karma.conf.js and add references of Angular and Angular Mock. Your Files sections should look like the image below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">files: [\n      'node_modules\/angular\/angular.js',\n      'node_modules\/angular-mocks\/angular-mocks.js',\n      'app\/*.js',\n      'tests\/*Test.js'\n    ],<\/pre>\n\n\n\n<p>Next go back to command prompt and run the command<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">karma start <\/pre>\n\n\n\n<p>As soon as we run the karma start command, tests will start executing and we can see test results on the command prompt as shown in the image below.&nbsp; As you change the code and save the file, the test will be executed automatically.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/4431.pic11.png\" alt=\" As you change the code and save the file, the test will be executed automatically\" title=\"As you change the code and save the file, the test will be executed automatically\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-15\">Step 15<\/h2>\n\n\n\n<p>Now let\u2019s write a unit test for the AngularJS Controller. Add the following test to <b>CalculatorAppTest.js<\/b> and add a test for the controller below to the filter test or below the filter test describe.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">describe('addcontrollertest', function () {\n        var $controller;\n        beforeEach(inject(function (_$controller_) {\n            $controller = _$controller_;\n        }));\n        it('1 + 1 should equal 2', function () {\n            var $scope = {};\n            var controller = $controller('CalculatorController', { $scope: $scope });\n            $scope.num1 = 1;\n            $scope.num2 = 2;\n            $scope.add();\n            expect($scope.sum).toBe(3);\n        });\n    });<\/pre>\n\n\n\n<p>We are creating a proxy of the controller and injecting that using ng-mock $controller service.&nbsp; Once the controller is injected, take the reference of CalculatorController (controller in the test here) and calling the add method.&nbsp; At this point the test will fail, since we have not written controller yet.&nbsp; Karma is giving the failure message that CalculatorController is not a function.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/0726.pic12.png\" alt=\" At this point the test will fail, since we have not written controller yet.\u00a0 Karma is giving the failure message that CalculatorController is not a function.\" title=\"At this point the test will fail, since we have not written controller yet.\u00a0 Karma is giving the failure message that CalculatorController is not a function.\"\/><\/figure>\n\n\n\n<p>Next let us go ahead and write the controller in the \u2018MyApp\u2019 module.<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">MyApp.controller('CalculatorController', function ($scope) {\n    $scope.add = function () {\n        $scope.sum = $scope.num1 + $scope.num2;\n    }\n});<\/pre>\n\n\n\n<p>As soon as we save the CalculatorApp.js file after writing the controller, the test will pass as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/7242.pic13.png\" alt=\" As soon as we save the CalculatorApp.js file after writing the controller, the test will pass\" title=\"As soon as we save the CalculatorApp.js file after writing the controller, the test will pass\"\/><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"step-16-testing-angularjs-factory-with-local-data\">Step 16: Testing AngularJS Factory with local data \u00a0<\/h2>\n\n\n\n<p>Let us say that we have created an AngularJS service using factory method name PlayerLocalApi. This service is returning local data which is hard coded as of now. The Service is created as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">MyApp.factory('PlayerLocalApi', function () {\n    \/\/var data = [{ \"Name\": \"Dhananjay Kumar\", \"Age\": 33.0 }];\n    var data = [{ \"Id\": \"1\", \"Name\": \"Dhananjay Kumar\", \"Age\": 33.0 }, { \"Id\": \"2\", \"Name\": \"Sachin Tendulkar\", \"Age\": 22.0 }, { \"Id\": \"6\", \"Name\": \"rahul dravid\", \"Age\": 60.0 }];\n    var PlayerLocalApi = {};\n    PlayerLocalApi.getPlayers = function () {\n        return data;\n    }\n\n    return PlayerLocalApi;\n});<\/pre>\n\n\n\n<p>We can write a unit test to test the service as shown in the listing below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">describe('playerservicetest', function () {\n        var data = [{ \"Id\": \"1\", \"Name\": \"Dhananjay Kumar\", \"Age\": 33.0 }, { \"Id\": \"2\", \"Name\": \"Sachin Tendulkar\", \"Age\": 22.0 }, { \"Id\": \"6\", \"Name\": \"rahul dravid\", \"Age\": 60.0 }];\n        var PlayerLocalApi = {};\n\n        beforeEach(inject(function (_PlayerLocalApi_) {\n            PlayerLocalApi = _PlayerLocalApi_;\n        }));\n        it('should return search player data', function () {\n            expect(PlayerLocalApi.getPlayers()).toEqual(data);\n\n        });\n    });<\/pre>\n\n\n\n<p>In the above code snippet, we are injecting the service PlayerLocalApi and then calling getPlayers on that. Also, we have exact test data to test the data returns from the service. This test will pass.<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/0207.pic14.png\" alt=\" \"\/><\/figure>\n\n\n\n<p>Just to make sure that we have written the test correctly, go back to service and comment the second data and uncomment the first data so the modified service is as listed below:<\/p>\n\n\n\n<pre class=\"EnlighterJSRAW\" data-enlighter-language=\"generic\" data-enlighter-theme=\"\" data-enlighter-highlight=\"\" data-enlighter-linenumbers=\"\" data-enlighter-lineoffset=\"\" data-enlighter-title=\"\" data-enlighter-group=\"\">MyApp.factory('PlayerLocalApi', function () {\n    var data = [{ \"Name\": \"Dhananjay Kumar\", \"Age\": 33.0 }];\n   \/\/var data = [{ \"Id\": \"1\", \"Name\": \"Dhananjay Kumar\", \"Age\": 33.0 }, { \"Id\": \"2\", \"Name\": \"Sachin Tendulkar\", \"Age\": 22.0 }, { \"Id\": \"6\", \"Name\": \"rahul dravid\", \"Age\": 60.0 }];\n    var PlayerLocalApi = {};\n    PlayerLocalApi.getPlayers = function () {\n        return data;\n    }\n\n    return PlayerLocalApi;\n});<\/pre>\n\n\n\n<p>Now the service is returning data which is not the same as test data in the test so we will get a failed test as shown in the image below:<\/p>\n\n\n\n<figure class=\"wp-block-image\"><img decoding=\"async\" src=\"\/community\/cfs-filesystemfile\/__key\/CommunityServer.Blogs.Components.WeblogFiles\/dhananjay_5F00_kumar.angularunittest2\/7651.pic15.png\" alt=\" Now the service is returning data which is not the same as test data in the test so we will get a failed test\" title=\"Now the service is returning data which is not the same as test data in the test so we will get a failed test\"\/><\/figure>\n\n\n\n<p>And that\u2019s how to write unit tests for services returning local data.<\/p>\n\n\n\n<h2 class=\"wp-block-heading\" class=\"wp-block-heading\" id=\"conclusion\">Conclusion <\/h2>\n\n\n\n<p>In this post we covered a lot! We learned how to:<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>Set up a development environment<\/li>\n\n\n\n<li>Set up a test environment for jasmine<\/li>\n\n\n\n<li>Setup a karma test runner environment<\/li>\n\n\n\n<li>Write unit tests for filter, controller, and service<\/li>\n<\/ul>\n\n\n\n<p>In further posts, we will see how to write unit tests for $http, $q services etc. I hope you find this post useful. Thanks for reading!<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn how to write unit tests with jasmine, how to run them with karma, and how to create proxies of AngularJS controls like filter, controller, and more.<\/p>\n","protected":false},"author":65,"featured_media":2366,"comment_status":"publish","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[7,17],"tags":[],"class_list":["post-595","post","type-post","status-publish","format-standard","has-post-thumbnail","hentry","category-angular","category-how-to"],"_links":{"self":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/595","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/users\/65"}],"replies":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/comments?post=595"}],"version-history":[{"count":2,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/595\/revisions"}],"predecessor-version":[{"id":2007,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/posts\/595\/revisions\/2007"}],"wp:featuredmedia":[{"embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media\/2366"}],"wp:attachment":[{"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/media?parent=595"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/categories?post=595"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.infragistics.com\/blogs\/wp-json\/wp\/v2\/tags?post=595"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}