Wednesday, 25 May 2016

Steps involved in testing of input file element

Steps:

 1. Let us assume we have a component named as fileOperation:  
     export class FileOperationComponent {  
           isImportSuccessful : boolean  
           constructor(){  
              this.isImportSuccessful=false;  
           }  
    //We will be mocking this Methods and we assume that when the user Clicks on the file   browser this method gets called.  
        importFile(input:HTMLInputElement) {  
           let file = input.files[0];  
           //This is used to read the file  
           let json:string;  
           let reader = new FileReader();  
           reader.onload = (e) => {   
           this.isImportSuccessful=true;  
           };  
           reader.readAsText(file);  
        }  
 2. Now we will create a spec file fileOperation.component.spec as follows:  
 **The solution which is provided here will be useful untill code coverage is concerned.  
   import {ReflectiveInjector, provide, bind} from "@angular/core";  
   import {it, describe, expect, beforeEach, inject, beforeEachProviders} from "@angular/core/testing";  
   import {RouteSegment, RouteTree, OnActivate} from "@angular/router";  
 //Now we will mock the HTMLInputElement so that we can send a mock file during our testing, here it goes.  
   class MockHTMLInput {  
     files: Array<File>;  
     constructor() {  
       this.files = new Array<File>();  
       let content = "Hello World";  
       let data = new Blob([content], { type: 'text/plain' });  
       let arrayOfBlob = new Array<Blob>();  
       arrayOfBlob.push(data);  
       let file = new File(arrayOfBlob, "Mock.csv");  
       this.files.push(file);  
     }  
   }  
   //The Test case begins here   
   describe('File Operation Component test', () => {  
     let fileOperationComponent : FileOperationComponent;   
     let mockFileInput: HTMLInputElement;   
     beforeEachProviders(() => [  
       provide(HTMLInputElement, { useClass: MockHTMLInput })  
     ]);  
     beforeEach(inject([  
       HTMLInputElement  
     ],  
        (mockHtmlInputElement:HTMLInputElement) => {  
         fileOperationComponent = new FileOperationComponent ();  
         mockFileInput=mockHtmlInputElement  
     }));  
     it('should call the importFile successfully', () =>{  
       fileOperationComponent .importFile(mockFileInput);  
       //TODO: In future need to change if any test case available to support call backfunctions.  
       expect(true).toBe(true); // This will fail if any other assertion are kept as the FileReader onload function is a callback function and we don't have any probable way to test that.  
     });  
   }); 

 In future , I will provide how to mock the call back functions for now at least you can crawl inside the function.

1 comment: