Categories: JavascriptTestingUI

AngularJS Hello World Unit Testing Code Example

The article intends to provide take away code to get started with unit testing while working with AngularJS. The underlying Javascript unit testing framework used for testing the AngularJS code sample is Jasmine.

  • Controllers.js
  • ControllersSpecs.js

You may want to pay attention to some of the following facts in relation with unit testing vis-a-vis unit testing controller methods:

  • Use AngularJS dependency injection feature to pass on dependencies to Angular components such as controller, filters, directives etc. Following code does the magic of injecting $rootScope and $controller which is also represented in the code samples later in this article. For rookies, following should be sufficient for cut-copy-paste to get started with unit testing.
     // Module helloApp initialized
     //
     module("helloApp");
     // Controller and rootScope injected for initializing
     // the controller and working with scope object in "it" function blocks
     //
     inject(function($controller, $rootScope){
         $scope = $rootScope.$new();
         $controller( "HelloCtrl", {$scope:$scope});
        });
  • In Angular, the controllers are strictly separated from the DOM manipulation logic and this results in a much easier testability. You would not see any HTML code in the example shown below.

 

Controllers.js

Following represents the AngularJS code representing Hello world app consisting of one function named as addProfile. The demo apps could be found on following pages:

var helloApp = angular.module("helloApp", []);
helloApp.controller("HelloCtrl", function($scope) {
 $scope.name = "Calvin Hobbes";
 $scope.profiles = [];

 $scope.addProfile = function(){
  var profile = {firstname:$scope.firstname,lastname:$scope.lastname,email:$scope.email};
  $scope.profiles.push( profile );
 }
});

 

ControllersSpecs.js

Following represents the Jasmine code sample used to test the above code. Pay attention to “BeforeEach” setup function which initializes the HelloApp and create a controller with name “HelloCtrl”. Note that the HTML page should consist of directives such as ng-app=”helloApp” and ng-controller=”HelloCtrl” appropriately.

describe( "HelloWorld Controller", function() {
    //
    // Defining the scope variable to be accessed within "it" function
    // blocks
    //
    var $scope;
    //
    // Setup function called prior to each "it" function block
    //
    beforeEach(function(){
       // Module helloApp initialized
       //
       module("helloApp");
       // Controller and rootScope injected for initializing
       // the controller and working with scope object in "it" function blocks
       //
       inject(function($controller, $rootScope){
   $scope = $rootScope.$new();
       $controller( "HelloCtrl", {$scope:$scope});
       });
    });

    it( "should have default name set to Calvin Hobbes", function() {
        expect($scope.name).toEqual("Calvin Hobbes");
 });

 it( "should have an empty profiles array to store profiles", function() {
     expect($scope.profiles.length).toEqual(0);
 });

 it( "should add a profile to profiles store", function(){
     $scope.firstname = "Chris";
     $scope.lastname = "Johnson";
     $scope.email = "chris.johnson@gmail.com";

     $scope.addProfile();
     //
     // Expectations
     //
     expect( $scope.profiles.length ).toEqual(1);
     expect( $scope.profiles[0].firstname ).toEqual( "Chris" );
     expect( $scope.profiles[0].lastname ).toEqual( "Johnson" );
     expect( $scope.profiles[0].email ).toEqual( "chris.johnson@gmail.com" );
 });
});

 

 

How to Run Above Tests

We recommend you to get setup with Karma & Jasmine using instructions that could be found on following page: http://vitalflux.com/angularjs-7-steps-unit-testing-angularjs-scripts-jasmine/

[adsenseyu1]

Ajitesh Kumar

I have been recently working in the area of Data analytics including Data Science and Machine Learning / Deep Learning. I am also passionate about different technologies including programming languages such as Java/JEE, Javascript, Python, R, Julia, etc, and technologies such as Blockchain, mobile computing, cloud-native technologies, application security, cloud computing platforms, big data, etc. For latest updates and blogs, follow us on Twitter. I would love to connect with you on Linkedin. Check out my latest book titled as First Principles Thinking: Building winning products using first principles thinking. Check out my other blog, Revive-n-Thrive.com

Share
Published by
Ajitesh Kumar

Recent Posts

Mean Squared Error vs Cross Entropy Loss Function

Last updated: 28th April, 2024 As a data scientist, understanding the nuances of various cost…

2 days ago

Cross Entropy Loss Explained with Python Examples

Last updated: 28th April, 2024 In this post, you will learn the concepts related to…

2 days ago

Logistic Regression in Machine Learning: Python Example

Last updated: 26th April, 2024 In this blog post, we will discuss the logistic regression…

4 days ago

MSE vs RMSE vs MAE vs MAPE vs R-Squared: When to Use?

Last updated: 22nd April, 2024 As data scientists, we navigate a sea of metrics to…

5 days ago

Gradient Descent in Machine Learning: Python Examples

Last updated: 22nd April, 2024 This post will teach you about the gradient descent algorithm…

1 week ago

Loss Function vs Cost Function vs Objective Function: Examples

Last updated: 19th April, 2024 Among the terminologies used in training machine learning models, the…

2 weeks ago