Learn Angular 4.0 In 10 Days - Unit Test - Day Ten (Part One)

Let us start day 10 (the last part) of the "Learning Angular 4.0 in 10 Days" series. In the previous article, we discussed about Route Process in Angular 4.0. If you want to read the previous articles of this series, do visit the below links.

In this Angular 4.0 series, we have already discussed different types of basic and advanced concepts or features of AngularJs 4.0 like data binding, directives, pipes, service, route, HTTP modules, pipes, etc. Now in this article, we will discuss one of the main advantages of Angular 4.0; i.e., Unit Testing, because the Angular Framework has been designed with testability as a primary objective.

Nowadays, JavaScript has become the de facto programming language to build and empower front end/ web applications. We can use JavaScript to develop simple or complex applications. However, applications in production are often vulnerable to bugs caused by design inconsistencies, logical implementation errors, and similar issues. For this reason, it is usually difficult to predict how applications will behave in real-time environments, which leads to unexpected behavior, non-availability of applications, or outages for short or long durations. This generates lack of confidence and dissatisfaction among application users. Also, high cost is often associated with fixing the production bugs. Therefore, there is a need to develop applications that are of a high quality and that offer high availability.

Test-Driven-Development is an engineering process in which the developer writes an initial automated test case that defines a feature, then writes the minimum amount of code to pass the test and eventually refactors the code to acceptable standards. 

Now, when we talk about testing in Angular, we basically point out two different types of Testing.

Unit Testing

A unit test is used to test individual components of the system. That’s why unit testing is basically called Isolated Testing. It is the best practice of testing small isolated pieces of code. If our unit testing depends on some external resources like database, network, apis then it is not a unit test.

An integration test is a test which tests the system as a whole, and how it will run in production. Unit tests should only verify the behavior of a specific unit of code. If the unit's behavior is modified, then the unit test would be updated as well. Unit tests should not make assumptions about the behavior of other parts of your codebase or your dependencies. When other parts of your codebase are modified, your unit tests should not fail. (Any failure indicates a test that relies on other components and is therefore not a unit test.) Unit tests are cheap to maintain and should only be updated when the individual units are modified. For TDD in Angular, a unit is most commonly defined as a class, pipe, component, or service. It is important to keep units relatively small. This helps you write small tests which are "self-documenting", where they are easy to read and understand.

Functional Testing

Functional testing is defined as the testing the complete functionality or functional flow of an application. In case of web applications, this means interacting the different UI of the web applications as it is running by the user in the browser in real life. This is also called End To End Testing (E22 Testing).

The Testing Toolchain

Our testing toolchain consists of the following tools.

  • Jasmine
  • Karma
  • Phantom-js
  • Istanbul
  • Sinon
  • Chai
In this article, we use Jasmine and Karma for performing the unit test in Angular 4.

Jasmine

Jasmine is the most popular Javascript testing framework in the Angular community. This testing framework supports a software development practice which is called Behavior Driven Development or BDD. This is one the main features of Test Driven Development (TDD). This is the core framework that we will write our unit tests with. Basically, Jasmine & BDD basically try to describe a test method case in a human readable pattern so that any user include any non-technical personal can identified what is going on. Jasmine tests are written using JavaScript functions, which makes writing tests a nice extension of writing application code. There are several Jasmine functions in the example, which I have described below.

NameDescriptions
describeGroups a number of related tests (this is optional, but it helps organize test code). Basically, test suites need to call this function with two parameters – a string (for test name or test description) and a function.
beforeEachExecutes a function before each test (this is often used for the arranging part of a test)
itExecutes a function to form a test (the active part of the test)
expectIdentifies the result from the test (part of the assert stage)
toEqualCompares the result from the test to the expected value (the other part of the asset)
beforeAllThis function is called once before all the specs in describe test suite are run

The basic sequence to pay attention to is that this function executes a test function so that the "expect" and toEqual functions can be used to assess the result. The toEqual function is only one way that Jasmine can evaluate the result of a test. I have listed the other available functions as below.

NameDescriptions
expect(x).toEqual(val)Asserts that x has the same value as val (but not necessarily the same object)
expect(x).toBe(obj)Asserts that x and obj are the same object
expect(x).toMatch(regexp)Asserts that x matches the specified regular expression
expect(x).toBeDefined()Asserts that x has been defined
expect(x).toBeUndefined()Asserts that x has not been defined
expect(x).toBeNull()Asserts that x is null
expect(x).toBeTruthy()Asserts that x is true or evaluates to true
expect(x).toBeFalsy()Asserts that x is false or evaluates to false
expect(x).toContain(y)Asserts that x is a string that contains y
expect(x).toBeGreaterThan(y)Asserts that x is greater than y
expect(fn).toThrow(string);Asserts to capture any throw of the given function
expect(fn).toThrowError(string);Asserts to capture any exception error

Karma

Karma is a test automation tool for controlling the execution of our tests and what browser to perform them under. It also allows us to generate various reports on the results. For one or two tests this may seem like overkill, but as an application grows larger and the number of units to test grows, it is important to organize, execute and report on tests in an efficient manner. Karma is library agnostic so we could use other testing frameworks in combination with other tools (like code coverage reports, spy testing, e2e, etc.).

In order to test our Angular application, we must create an environment for it to run in. We could use a browser like Chrome or Firefox to accomplish this (Karma supports in-browser testing), or we could use a browser-less environment to test our application, which can offer us greater control over automating certain tasks and managing our testing workflow. PhantomJS provides a JavaScript API that allows us to create a headless DOM instance which can be used to bootstrap our Angular application. Then, using that DOM instance that is running our Angular application, we can run our tests.

Karma is basically a tool which lets us spawn browsers and run all jasmine tests inside of them which are executed from the command line. This results of the tests are also displayed on the command line. Karma also watches our development file changes and re-runs the test automatically.

Istanbul is used by Karma to generate code coverage reports, which tells us the overall percentage of our application being tested. This is a great way to track which components/services/pipes/etc. have tests written and which don't. We can get some useful insight into how much of the application is being tested and where.

Why is Unit Testing required?

  • Guards or protects the existing code which can be broken due to any changes.
  • Integrate automatic build process to automate the pipeline of resource publish at any time.
  • Clarifies what the code does both when used as intended and when faced with deviant conditions. They serve as a form of documentation for your code.
  • Reveals mistakes in design and implementation. When a part of the application seems hard to test, the root cause is often a design flaw, something to cure now rather than later when it becomes expensive to fix.
  • It allows us to test the interaction of directives or components with its template URL.
  • It allows us to easily track the change detection.
  • It also allows us to use and test Angular Dependency Integration framework.

Filename Conventions

Each unit test is put into its own separate file. The Angular team recommends putting unit test scripts alongside the files they are testing and using a .spec filename extension to mark it as a testing script (this is a Jasmine convention). So if you had a component /app/components/mycomponent.ts, then your unit test for this component would be in /app/components/mycomponent.spec.ts. This is a matter of personal preference; you can put your testing scripts wherever you like, though keeping them close to your source files makes them easier to find and gives those who aren't familiar with the source code an idea of how that particular piece of code should work.

ANGULAR TEST BED

Angular Test Bed (ATB) is one of the higher level Angular Only testing frameworks which allows us to pass data to the test environment and can easily test behaviors that depend on the Angular Framework.

When to use Angular Test Bed

Actually, we need to use the Angular Test Bed process for performing unit testing as per the below reasons –

  1. This process allows us to test the interaction of a component or directives with its templates
  2. It also allows us to easily test change detection mechanism of the angular
  3. It also allows us to test the Dependency Injection process
  4. It allows us to run the test using NgModule configuration which we use in our application
  5. It allows us to test user interactions including clicks and input field operation.

OUR FIRST UNIT TEST

For starting the unit test, first, we need to configure the environment for the unit Test. For configuring the Unit Test Project, we need to create a folder structure just as below.

 
  • App Folder contains both Angular and Unit Test Specs
  • Component folder contains all the components which we need to unit test
  • Specs folder contains all the Angular test bed unit test models
Sample Code of tsconfig.json
  1. {  
  2.   "compilerOptions": {  
  3.     "target""es5",  
  4.     "module""commonjs",  
  5.     "moduleResolution""node",  
  6.     "sourceMap"true,  
  7.     "emitDecoratorMetadata"true,  
  8.     "experimentalDecorators"true,  
  9.     "lib": [  
  10.       "es2015",  
  11.       "dom"  
  12.     ],  
  13.     "noImplicitAny"true,  
  14.     "suppressImplicitAnyIndexErrors"true,  
  15.     "typeRoots": [  
  16.       "../node_modules/@types/"  
  17.     ]  
  18.   },  
  19.   "compileOnSave"true,  
  20.   "exclude": [  
  21.     "node_modules/*"  
  22.   ]  
  23. }  
Sample code of systemjs.config.js file
  1. (function (global) {  
  2.     System.config({  
  3.       transpiler: 'ts',  
  4.       typescriptOptions: {  
  5.         "target""es5",  
  6.         "module""commonjs",  
  7.         "moduleResolution""node",  
  8.         "sourceMap"true,  
  9.         "emitDecoratorMetadata"true,  
  10.         "experimentalDecorators"true,  
  11.         "lib": ["es2015""dom"],  
  12.         "noImplicitAny"true,  
  13.         "suppressImplicitAnyIndexErrors"true  
  14.       },  
  15.       meta: {  
  16.         'typescript': {  
  17.           "exports""ts"  
  18.         }  
  19.       },  
  20.       paths: {  
  21.         // paths serve as alias  
  22.         'npm:''https://unpkg.com/'  
  23.       },  
  24.       map: {  
  25.         'app''app',  
  26.     
  27.         // angular bundles  
  28.         '@angular/animations''npm:@angular/animations/bundles/animations.umd.js',  
  29.         '@angular/animations/browser''npm:@angular/animations/bundles/animations-browser.umd.js',  
  30.         '@angular/core''npm:@angular/core/bundles/core.umd.js',  
  31.         '@angular/common''npm:@angular/common/bundles/common.umd.js',  
  32.         '@angular/common/http''npm:@angular/common/bundles/common-http.umd.js',  
  33.         '@angular/compiler''npm:@angular/compiler/bundles/compiler.umd.js',  
  34.         '@angular/platform-browser''npm:@angular/platform-browser/bundles/platform-browser.umd.js',  
  35.         '@angular/platform-browser/animations''npm:@angular/platform-browser/bundles/platform-browser-animations.umd.js',  
  36.         '@angular/platform-browser-dynamic''npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',  
  37.         '@angular/http''npm:@angular/http/bundles/http.umd.js',  
  38.         '@angular/router''npm:@angular/router/bundles/router.umd.js',  
  39.         '@angular/router/upgrade''npm:@angular/router/bundles/router-upgrade.umd.js',  
  40.         '@angular/forms''npm:@angular/forms/bundles/forms.umd.js',  
  41.         '@angular/upgrade''npm:@angular/upgrade/bundles/upgrade.umd.js',  
  42.         '@angular/upgrade/static''npm:@angular/upgrade/bundles/upgrade-static.umd.js',  
  43.     
  44.         // other libraries  
  45.         'rxjs':                      'npm:[email protected]',  
  46.         'rxjs/operators':            'npm:[email protected]/operators/index.js',  
  47.         'tslib':                     'npm:tslib/tslib.js',  
  48.         'angular-in-memory-web-api''npm:[email protected]/bundles/in-memory-web-api.umd.js',  
  49.         'ts':                        'npm:[email protected]/lib/plugin.js',  
  50.         'typescript':                'npm:[email protected]/lib/typescript.js',  
  51.     
  52.       },  
  53.       // packages tells the System loader how to load when no filename and/or no extension  
  54.       packages: {  
  55.         app: {  
  56.           main: './main.ts',  
  57.           defaultExtension: 'ts',  
  58.           meta: {  
  59.             './*.ts': {  
  60.               loader: 'systemjs-angular-loader.js'  
  61.             }  
  62.           }  
  63.         },  
  64.         rxjs: {  
  65.           defaultExtension: 'js'  
  66.         }  
  67.       }  
  68.     });  
  69.     
  70.   })(this);  
Sample Code of systemjs-angularjs-loader.js
  1. var templateUrlRegex = /templateUrl\s*:(\s*['"`](.*?)['"`]\s*)/gm;  
  2. var stylesRegex = /styleUrls *:(\s*\[[^\]]*?\])/g;  
  3. var stringRegex = /(['`"])((?:[^\\]\\\1|.)*?)\1/g;  
  4.   
  5. module.exports.translate = function(load){  
  6.   if (load.source.indexOf('moduleId') != -1) return load;  
  7.   
  8.   var url = document.createElement('a');  
  9.   url.href = load.address;  
  10.   
  11.   var basePathParts = url.pathname.split('/');  
  12.   
  13.   basePathParts.pop();  
  14.   var basePath = basePathParts.join('/');  
  15.   
  16.   var baseHref = document.createElement('a');  
  17.   baseHref.href = this.baseURL;  
  18.   baseHref = baseHref.pathname;  
  19.   
  20.   if (!baseHref.startsWith('/base/')) { // it is not karma  
  21.     basePath = basePath.replace(baseHref, '');  
  22.   }  
  23.   
  24.   load.source = load.source  
  25.     .replace(templateUrlRegex, function(match, quote, url){  
  26.       var resolvedUrl = url;  
  27.   
  28.       if (url.startsWith('.')) {  
  29.         resolvedUrl = basePath + url.substr(1);  
  30.       }  
  31.   
  32.       return 'templateUrl: "' + resolvedUrl + '"';  
  33.     })  
  34.     .replace(stylesRegex, function(match, relativeUrls) {  
  35.       var urls = [];  
  36.   
  37.       while ((match = stringRegex.exec(relativeUrls)) !== null) {  
  38.         if (match[2].startsWith('.')) {  
  39.           urls.push('"' + basePath + match[2].substr(1) + '"');  
  40.         } else {  
  41.           urls.push('"' + match[2] + '"');  
  42.         }  
  43.       }  
  44.   
  45.       return "styleUrls: [" + urls.join(', ') + "]";  
  46.     });  
  47.   
  48.   return load;  
  49. };  
Sample Code of Style.css
  1. /* Master Styles */  
  2. h1 {  
  3.     color: #369;  
  4.     font-family: Arial, Helvetica, sans-serif;  
  5.     font-size: 250%;  
  6.   }  
  7.   h2, h3 {  
  8.     color: #444;  
  9.     font-family: Arial, Helvetica, sans-serif;  
  10.     font-weight: lighter;  
  11.   }  
  12.   body {  
  13.     margin: 2em;  
  14.   }  
  15.   body, input[text], button {  
  16.     color: #888;  
  17.     font-family: Cambria, Georgia;  
  18.   }  
  19.   a {  
  20.     cursor: pointer;  
  21.     cursor: hand;  
  22.   }  
  23.   button {  
  24.     font-family: Arial;  
  25.     background-color: #eee;  
  26.     border: none;  
  27.     padding: 5px 10px;  
  28.     border-radius: 4px;  
  29.     cursor: pointer;  
  30.     cursor: hand;  
  31.   }  
  32.   button:hover {  
  33.     background-color: #cfd8dc;  
  34.   }  
  35.   button:disabled {  
  36.     background-color: #eee;  
  37.     color: #aaa;  
  38.     cursor: auto;  
  39.   }  
  40.     
  41.   /* Navigation link styles */  
  42.   nav a {  
  43.     padding: 5px 10px;  
  44.     text-decoration: none;  
  45.     margin-top: 10px;  
  46.     display: inline-block;  
  47.     background-color: #eee;  
  48.     border-radius: 4px;  
  49.   }  
  50.   nav a:visited, a:link {  
  51.     color: #607D8B;  
  52.   }  
  53.   nav a:hover {  
  54.     color: #039be5;  
  55.     background-color: #CFD8DC;  
  56.   }  
  57.   nav a.active {  
  58.     color: #039be5;  
  59.   }  
  60.     
  61.   /* items class */  
  62.   .items {  
  63.     margin: 0 0 2em 0;  
  64.     list-style-type: none;  
  65.     padding: 0;  
  66.     width: 24em;  
  67.   }  
  68.   .items li {  
  69.     cursor: pointer;  
  70.     position: relative;  
  71.     left: 0;  
  72.     background-color: #EEE;  
  73.     margin: .5em;  
  74.     padding: .3em 0;  
  75.     height: 1.6em;  
  76.     border-radius: 4px;  
  77.   }  
  78.   .items li:hover {  
  79.     color: #607D8B;  
  80.     background-color: #DDD;  
  81.     left: .1em;  
  82.   }  
  83.   .items li.selected:hover {  
  84.     background-color: #BBD8DC;  
  85.     color: white;  
  86.   }  
  87.   .items .text {  
  88.     position: relative;  
  89.     top: -3px;  
  90.   }  
  91.   .items {  
  92.     margin: 0 0 2em 0;  
  93.     list-style-type: none;  
  94.     padding: 0;  
  95.     width: 24em;  
  96.   }  
  97.   .items li {  
  98.     cursor: pointer;  
  99.     position: relative;  
  100.     left: 0;  
  101.     background-color: #EEE;  
  102.     margin: .5em;  
  103.     padding: .3em 0;  
  104.     height: 1.6em;  
  105.     border-radius: 4px;  
  106.   }  
  107.   .items li:hover {  
  108.     color: #607D8B;  
  109.     background-color: #DDD;  
  110.     left: .1em;  
  111.   }  
  112.   .items li.selected {  
  113.     background-color: #CFD8DC;  
  114.     color: white;  
  115.   }  
  116.     
  117.   .items li.selected:hover {  
  118.     background-color: #BBD8DC;  
  119.   }  
  120.   .items .text {  
  121.     position: relative;  
  122.     top: -3px;  
  123.   }  
  124.   .items .badge {  
  125.     display: inline-block;  
  126.     font-size: small;  
  127.     color: white;  
  128.     padding: 0.8em 0.7em 0 0.7em;  
  129.     background-color: #607D8B;  
  130.     line-height: 1em;  
  131.     position: relative;  
  132.     left: -1px;  
  133.     top: -4px;  
  134.     height: 1.8em;  
  135.     margin-right: .8em;  
  136.     border-radius: 4px 0 0 4px;  
  137.   }  
  138.   /* everywhere else */  
  139.   * {  
  140.     font-family: Arial, Helvetica, sans-serif;  
  141.   }  
Sample code of browser-test-shim.js
  1. (function () {  
  2.   
  3.     Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.  
  4.       
  5.     // Uncomment to get full stacktrace output. Sometimes helpful, usually not.  
  6.     // Error.stackTraceLimit = Infinity; //  
  7.       
  8.     jasmine.DEFAULT_TIMEOUT_INTERVAL = 3000;  
  9.       
  10.     var baseURL = document.baseURI;  
  11.     baseURL = baseURL + baseURL[baseURL.length-1] ? '' : '/';  
  12.       
  13.     System.config({  
  14.       baseURL: baseURL,  
  15.       // Extend usual application package list with test folder  
  16.       packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } },  
  17.       
  18.       // Assume npm: is set in `paths` in systemjs.config  
  19.       // Map the angular testing umd bundles  
  20.       map: {  
  21.         '@angular/core/testing''npm:@angular/core/bundles/core-testing.umd.js',  
  22.         '@angular/common/testing''npm:@angular/common/bundles/common-testing.umd.js',  
  23.         '@angular/compiler/testing''npm:@angular/compiler/bundles/compiler-testing.umd.js',  
  24.         '@angular/platform-browser/testing''npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',  
  25.         '@angular/platform-browser-dynamic/testing''npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',  
  26.         '@angular/http/testing''npm:@angular/http/bundles/http-testing.umd.js',  
  27.         '@angular/router/testing''npm:@angular/router/bundles/router-testing.umd.js',  
  28.         '@angular/forms/testing''npm:@angular/forms/bundles/forms-testing.umd.js',  
  29.       },  
  30.     });  
  31.       
  32.     System.import('systemjs.config.js')  
  33.       //.then(importSystemJsExtras)  
  34.       .then(initTestBed)  
  35.       .then(initTesting);  
  36.       
  37.     /** Optional SystemJS configuration extras. Keep going w/o it */  
  38.     function importSystemJsExtras(){  
  39.       return System.import('systemjs.config.extras.js')  
  40.       .catch(function(reason) {  
  41.         console.log(  
  42.           'Warning: System.import could not load the optional "systemjs.config.extras.js". Did you omit it by accident? Continuing without it.'  
  43.         );  
  44.         console.log(reason);  
  45.       });  
  46.     }  
  47.       
  48.     function initTestBed(){  
  49.       return Promise.all([  
  50.         System.import('@angular/core/testing'),  
  51.         System.import('@angular/platform-browser-dynamic/testing')  
  52.       ])  
  53.       
  54.       .then(function (providers) {  
  55.         var coreTesting    = providers[0];  
  56.         var browserTesting = providers[1];  
  57.       
  58.         coreTesting.TestBed.initTestEnvironment(  
  59.           browserTesting.BrowserDynamicTestingModule,  
  60.           browserTesting.platformBrowserDynamicTesting());  
  61.       })  
  62.     }  
  63.       
  64.     // Import all spec files defined in the html (__spec_files__)  
  65.     // and start Jasmine testrunner  
  66.     function initTesting () {  
  67.       console.log('loading spec files: '+__spec_files__.join(', '));  
  68.       return Promise.all(  
  69.         __spec_files__.map(function(spec) {  
  70.           return System.import(spec);  
  71.         })  
  72.       )  
  73.       //  After all imports load,  re-execute `window.onload` which  
  74.       //  triggers the Jasmine test-runner start or explain what went wrong  
  75.       .then(success, console.error.bind(console));  
  76.       
  77.       function success () {  
  78.         console.log('Spec files loaded; starting Jasmine testrunner');  
  79.         window.onload();  
  80.       }  
  81.     }  
  82.       
  83.     })();  
Sample code of Index.html file
  1. <!-- Run application specs in a browser -->  
  2. <!DOCTYPE html>  
  3. <html>  
  4. <head>  
  5.   <script>document.write('<base href="' + document.location + '" />');</script>  
  6.   <title>Sample App Specs</title>  
  7.   <meta charset="UTF-8">  
  8.   <meta name="viewport" content="width=device-width, initial-scale=1">  
  9.   <link rel="stylesheet" href="./style.css">  
  10.   <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css">  
  11.   
  12. </head>  
  13. <body>  
  14.   <script src="https://unpkg.com/[email protected]/dist/system.src.js"></script>  
  15.   
  16.   <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js"></script>  
  17.   <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>  
  18.   <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js"></script>  
  19.   
  20.   <script src="https://unpkg.com/[email protected]"></script>  
  21.   
  22.   <script src="https://unpkg.com/[email protected]?main=browser"></script>  
  23.   <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js?main=browser"></script>  
  24.   <script src="https://unpkg.com/zone.js/dist/proxy.js?main=browser"></script>  
  25.   <script src="https://unpkg.com/zone.js/dist/sync-test.js?main=browser"></script>  
  26.   <script src="https://unpkg.com/zone.js/dist/jasmine-patch.js?main=browser"></script>  
  27.   <script src="https://unpkg.com/zone.js/dist/async-test.js?main=browser"></script>  
  28.   <script src="https://unpkg.com/zone.js/dist/fake-async-test.js?main=browser"></script>  
  29.   
  30.   <script>  
  31.     var __spec_files__ = [  
  32.      ... specs file name with path details  
  33.     ];  
  34.   </script>  
  35.   <script src="browser-test-shim.js"></script>  
  36. </body>  
  37.   
  38. </html>  

In the above index.html file, _spec_files variables are basically used to store the list of Angular unit test spec file details with a proper folder so that when we run this UI in the browser, it loads spec files one by one and executes them with the help of browser-test-shims.js file. In that file, initTesting() is basically initializing the Unit Test methods one by one. 

Now, perform the unit test. We first need to add a simple TypeScript class which basically performs the basic mathematical operations between two numbers.
 
Sample code of calculator.woinput.ts
  1. export class CalculatorWithoutInput {  
  2.     private _firstNumber:number=10;  
  3.     private _secondNumber:number=20;  
  4.     private _result : number = 0;  
  5.   
  6.     constructor(){}  
  7.   
  8.     public addNumbers():number{  
  9.         this._result = this._firstNumber + this._secondNumber;  
  10.         return this._result;  
  11.     }  
  12.   
  13.     public subtractNumbers():number{  
  14.         this._result = this._firstNumber - this._secondNumber;  
  15.         return this._result;  
  16.     }  
  17.   
  18.     public multiplyNumbers():number{  
  19.         this._result = this._firstNumber * this._secondNumber;  
  20.         return this._result;  
  21.     }  
  22. }  
Now, create another TypeScript file for defining the specs for the above class file.
 
Sample code of calculator.woinput.spec.ts
  1. import { CalculatorWithoutInput } from '../component/calculator.woinput';  
  2.   
  3. describe('Calcultor Without Inputs (Basic Class)', () => {  
  4.     let firstNumber :number = 0;  
  5.     let secondNumber :number = 0;  
  6.     let result : number = 0;  
  7.   
  8.     let objCaculator : CalculatorWithoutInput;  
  9.   
  10.     beforeEach(() => {   
  11.         this.objCaculator = new CalculatorWithoutInput();  
  12.     });  
  13.       
  14.     afterEach(() => {   
  15.         this.objCaculator=null;  
  16.         this.firstNumber=0;  
  17.         this.secondNumber=0;  
  18.         this.result=0;  
  19.     });  
  20.   
  21.     it('check number addition', () => {  
  22.         this.firstNumber=10;  
  23.         this.secondNumber=20;  
  24.         this.result=this.firstNumber + this.secondNumber;  
  25.         expect(this.objCaculator.addNumbers())  
  26.             .toEqual(this.result);  
  27.     });  
  28.   
  29.     it('check number Subtract', () => {  
  30.         this.firstNumber=10;  
  31.         this.secondNumber=20;  
  32.         this.result=this.firstNumber - this.secondNumber;  
  33.         expect(this.objCaculator.subtractNumbers())  
  34.             .toEqual(this.result);  
  35.     });  
  36.   
  37.     it('check number Multiply', () => {  
  38.         this.firstNumber=10;  
  39.         this.secondNumber=20;  
  40.         this.result=this.firstNumber * this.secondNumber;  
  41.         expect(this.objCaculator.multiplyNumbers())  
  42.             .toEqual(this.result);  
  43.     });  
  44. });  
Now, change the code of the index.html file as below.
  1. <script>  
  2.    var __spec_files__ = [  
  3.      'app/specs/calculator.woinput.spec'  
  4.    ];  
  5.  </script>  
Now, run the index.html file in the browser.

 
Now, let us change our Calculator Class as below so that we can pass numbers from unit test specs and check the result.
  1. export class Calculator {      
  2.   
  3.     constructor(){}  
  4.   
  5.     public addNumbers(firstNumber : number, secondNumber : number ):number{  
  6.         return firstNumber + secondNumber;  
  7.     }  
  8.   
  9.     public subtractNumbers(firstNumber : number, secondNumber : number ):number{  
  10.         return firstNumber - secondNumber;  
  11.     }  
  12.   
  13.     public multiplyNumbers(firstNumber : number, secondNumber : number ):number{  
  14.         return firstNumber * secondNumber;  
  15.     }  
  16. }  
So, for the above code, we also need to change our unit test specs as below.
  1. import { Calculator } from '../component/calculator';  
  2.   
  3. describe('Calcultor With Inputs (Basic Class)', () => {  
  4.     let firstNumber :number = 0;  
  5.     let secondNumber :number = 0;  
  6.     let result : number = 0;  
  7.   
  8.     let objCaculator : Calculator;  
  9.   
  10.     beforeEach(() => {   
  11.         this.objCaculator = new Calculator();  
  12.     });  
  13.       
  14.     afterEach(() => {   
  15.         this.objCaculator=null;  
  16.         this.firstNumber=0;  
  17.         this.secondNumber=0;  
  18.         this.result=0;  
  19.     });  
  20.   
  21.     it('check number addition', () => {  
  22.         this.firstNumber=10;  
  23.         this.secondNumber=20;  
  24.         this.result=this.firstNumber + this.secondNumber;  
  25.         expect(this.objCaculator.addNumbers(this.firstNumber, this.secondNumber))  
  26.             .toEqual(this.result);  
  27.     });  
  28.   
  29.     it('check number Subtract', () => {  
  30.         this.firstNumber=10;  
  31.         this.secondNumber=20;  
  32.         this.result=this.firstNumber - this.secondNumber;  
  33.         expect(this.objCaculator.subtractNumbers(this.firstNumber, this.secondNumber))  
  34.             .toEqual(this.result);  
  35.     });  
  36.   
  37.     it('check number Multiply', () => {  
  38.         this.firstNumber=10;  
  39.         this.secondNumber=20;  
  40.         this.result=this.firstNumber * this.secondNumber;  
  41.         expect(this.objCaculator.multiplyNumbers(this.firstNumber, this.secondNumber))  
  42.             .toEqual(this.result);  
  43.     });  
  44. });  
In Part 2 of this article, we will discuss about the following topics in detail:
  1. How to perform a unit test on an Angular component
  2. Unit Test of a Directives
  3. Unit Test of a Service


Similar Articles