Introduction
AngularJS always promotes and encourages the automated testing therefore the tests for the AngularJS code has been written in Jasmine. Jasmine is a framework for the testing of JavaScript code. Its a Behavior Driven Development (BDD) for testing JavaScript code. Basically, BDD is a software development process that has driven from Test Driven Development (TDD). AngularJS provides Jasmine extensions to developers for the best unit testing experience.
Karma supports so many testing frameworks. So, Jasmine is the default option for Karma. I will explain the concept to write unit test with the help of Jasmine framework.
describe function
It is a global function that is being defined in the Jasmine unit test. It takes two parameters - a string and a function.
- String: It is the name or description of the spec suit.
- Function: It encapsulates the unit test specs.
Example
- describe('Unit Test: MyController', function() {
- });
Define a Spec
Specs in Jasmine is being defined by it() function.
The it() function takes two arguments:
- title: It is a string title and a title or description of the specs.
- function: It contains one or more expectations. These expectations are basically functions. It returns true or false after execution.
Example
- describe('my spec desc', function()
- {
-
- it('spec definition', function()
- {
- expect(true).toBe(true);
- });
- });
Expectations
Expectation is a case in which developer expects some value or result at different stages of the application.
Expectation is being set using the expect() function. It takes an argument that is called actual value. So, it compares between the actual value and the expected value.
Example
- describe('my spec desc', function()
- {
-
- it('my spec definition', function()
- {
- expect(true).toBe(true);
- });
-
- it('my second spec definition', function()
- {
- expect(false).not.toBe(true);
- });
- });
matchers
toBe
It compares values like JavaScript operator ===.
Example
- describe('my spec description', function()
- {
- it('expectation description ', function()
- {
- var value = 10,
- another_value = value;
- expect(value).toBe(another_value);
- expect(value).not.toBe(null);
- });
- });
toEqual
It compares values and works for simple literals and variables.
Example
- describe('my spec desc', function()
- {
- it('my spec expectation', function()
- {
- var value = 10;
- expect(value).toEqual(10);
- });
- });
Jasmine has so many other matchers like the following:
- toBeDefined
- toBeUndefined
- toMatch
- toBeNull
- toBeTruty
- toBeFalsy
- toContain
- toBeLessThan
- toBeGraterThan
Unit Test Spec Explanation
Now, I will explain one basic Jasmine Unit Test spec related to an asynchronous service call that returns a promise.
Controller and Service: app.js
-
- var app = angular.module('myModule', []);
-
- app.controller('MainCtrl', function($scope, myService)
- {
- $scope.name = "Testing";
- $scope.temp = myService.myServiceData();
- });
-
- app.service('myService', function($q)
- {
- this.myServiceData = function()
- {
- var deferred = $q.defer();
- return deferred.promise;
- }
- });
Jasmine Unit Test Spec : appSpec.js
- describe('Unit Testing: MainCtrl', function()
- {
- var $scope = null;
- var ctrl = null;
- var mockMyService;
- var deferred;
- var $q;
- var data =
- {
- name: 'test'
- };
- var createController;
- beforeEach(module('myModule'));
- beforeEach(inject(function($rootScope, $controller, $q)
- {
- $scope = $rootScope.$new();
- $q = $q;
- mockMyService =
- {
- myServiceData: function() {}
- };
- deferred = $q.defer();
- spyOn(mockMyService, 'myServiceData').and.returnValue(deferred.promise);
- createController = function() {
- return $controller('MainCtrl',
- {
- $scope: $scope,
- myService: mockMyService
- });
- };
- }));
- it('Should call myServiceData()', function()
- {
- var resolvedValue;
- ctrl = createController();
- $scope.temp.then(function(value)
- {
- resolvedValue = value;
- });
- deferred.resolve(data);
- $scope.$digest();
- expect(mockMyService.myServiceData).toHaveBeenCalled();
- expect(resolvedValue).toEqual(data);
- });
- });
JasmineBootStrap.js
It will create the `HTMLReporter`, which Jasmine calls to provide results of each spec and each suite. The Reporter and the spec result to the user.
- (function()
- {
- var jasmineEnv = jasmine.getEnv();
- jasmineEnv.updateInterval = 250;
- var htmlReporter = new jasmine.HtmlReporter();
- jasmineEnv.addReporter(htmlReporter);
- jasmineEnv.specFilter = function(spec)
- {
- return htmlReporter.specFilter(spec);
- };
- var currentWindowOnload = window.onload;
- window.onload = function()
- {
- if (currentWindowOnload)
- {
- currentWindowOnload();
- }
- execJasmine();
- };
-
- function execJasmine()
- {
- jasmineEnv.execute();
- }
- })();
style.css:
It is just for the reporting of Jasmine Unit test report.
- body
- {
- background - color: skyblue;
- padding: 0;
- margin: 8 px;
- }
- .jasmine_reporter
- {
- background - color: #0094ff;
- padding: 0;
- margin: 0;
- }
index.html
It is the display html page for the spec report.
- <!DOCTYPE html>
- <html ng-app="myModule">
-
- <head>
- <meta charset="utf-8" />
- <title>AngularJS Unit Test with Jasmine!</title>
- <link data-require="jasmine" data-semver="2.0.0" rel="stylesheet" href="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine.css" />
- <script data-require="json2" data-semver="0.0.2012100-8" src="//cdnjs.cloudflare.com/ajax/libs/json2/20121008/json2.js"></script>
- <script data-require="jasmine" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine.js"></script>
- <script data-require="jasmine" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/jasmine-html.js"></script>
- <script data-require="jasmine@*" data-semver="2.0.0" src="//cdn.jsdelivr.net/jasmine/2.0.0/boot.js"></script>
- <script data-require="angular.js" data-semver="1.2.16" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.16/angular.min.js"></script>
- <script data-require="angular-mocks" data-semver="1.2.16" src="https://code.angularjs.org/1.2.16/angular-mocks.js"></script>
- <link rel="stylesheet" href="style.css" />
- <script src="app.js"></script>
- <script src="appSpec.js"></script>
- <script src="jasmineBootstrap.js"></script>
- </head>
-
- <body>
- <div id="container" ng-controller="MainCtrl">
- <h1>Unit Testing of a Service that Returns a Promise - Jasmine {{name}}</h1>
- </div>
- <div id="HTMLReporter" class="jasmine_reporter"></div>
- </body>
-
- </html>
Report
Conclusion
AngularJS community always promotes and encourage unit testing practice. So, they have written and enhanced framework in such way that it makes easy for the developer. And, Jasmine is a very good framework for the unit test. See the attached code.