Trying to write test cases for each line

  • wrote a test case for the jump method,
  • but it doesn't happen inside the onloadend seat.onloadend method when I see a code coverage report.
    • in createSpyObj i called loadend but still not in it
  • Can you guys tell me how to fix this.
  • by providing my code and test case below.
  • I am trying to read a test case for each line.
jumping(inputValue: any): void { var that = this; var file: File = inputValue.files[0]; var seat: FileReader = new FileReader(); seat.onloadend = (e) => { this.encodeBase64 = seat.result; that.fileSelect = $("#laptop").val().replace(/^.*\\/, ""); if (that.fileSelect == '') { that.dragDrop = that.swimming; } else { that.dragDrop = ""; that.dragDrop = that.fileSelect; } } $('.running').show(); if (inputValue.files.length > 0) { var wholeQuantity = 0; wholeQuantity = inputValue.files[0].size / 1048576; //size in mb if (wholeQuantity > 5) { $('.stars').show(); $("#laptop").val(''); this.fileSelect = ""; } seat.readAsDataURL(file); } } describe('Jasmine Unit Tests: hand-Basketball-Manage-mobiles', () => { let rainSPORTSService:SPORTSService; let SPORTSService: SPORTSService; let decodeService: DecodeService; let BasketballChainComponent: handBasketballChain; let kickViewrainsComponent: kickViewrains; let tiger: Componenttiger<handBasketballChain>; let raintiger: Componenttiger<kickViewrains>; let foodktiger: Componenttiger<foodkCarousel>; let kendotiger: Componenttiger<KendoGridComponent>; let foodkComponent:foodkCarousel; let kendoComponent:KendoGridComponent; beforeEach(async(() => { jasmine.DEFAULT_TIMEOUT_INTERVAL = 10000; TestBed.configureTestingModule({ imports: [HttpModule, FormsModule,BrowserModule ], declarations:[handBasketballChain, KendoGridComponent,ProgressCircle, kickViewrains,handLeftSliderComponent,foodkCarousel,kickmobiles], providers:[SPORTSService,DecodeService,recentPinnedHistoryService, {provide: Router, useClass: RouterModule}, validationService,saveService, ChainService] }).compileComponents().then(() =>{ foodktiger = TestBed.createComponent(foodkCarousel); kendotiger = TestBed.createComponent(KendoGridComponent); foodkComponent = foodktiger.componentInstance; kendoComponent = kendotiger.componentInstance; tiger = TestBed.createComponent(handBasketballChain); BasketballChainComponent = tiger.componentInstance; SPORTSService = tiger.debugElement.injector.get(SPORTSService); tiger.componentInstance.kickmobiles.SPORTSService=tiger.debugElement.injector.get(SPORTSService); tiger.componentInstance.kickViewrains.SPORTSService=tiger.debugElement.injector.get(SPORTSService); decodeService = tiger.debugElement.injector.get(DecodeService); BasketballChainComponent.inputfoodkCarousel = foodkComponent; //jasmine.createSpy('foodkCarousel');//.andCallFake(function(msg) { return this }); BasketballChainComponent.kickmobiles.gridkendo=kendoComponent; })} )); it('Read kick mobile', (done) => { let callFirstTime : boolean = true; let url= spyOn(BasketballChainComponent.kickmobiles.SPORTSService,'getResponse').and. callFake(() => { if(callFirstTime) { callFirstTime = false; // Invoked by detectChanges() return Observable.of([{ "mobileId": "100", "mobileName": "http://localhost:3000/assets/js/actualairings.json", "mobileType": "TITLE", "mobileData": "YWZjYXJlZ2Vyamh2dmFyZWdoYnZi", "notes": "", "notesId": "100", "elfDocID": "100", "url": "http://localhost:3000/upload", "date": "06/27/2017", "addedByName": "Kamal", "userID": "206509786", "operationType": "create" }]); } }); const fileReaderSpy = jasmine.createSpyObj('FileReader', ['readAsDataURL', 'onloadend']); spyOn(window, 'FileReader').and.returnValue(fileReaderSpy); BasketballChainComponent.kickmobiles.jumping({ files: "Untitled-2.txt" }); var seat = new FileReader(); //seat.onloadend(e); //BasketballChainComponent.kickmobiles.jumping.onloadend() tiger.whenStable().then(() => { done(); }); }); }); 
+4
source share
1 answer

Remember that the key to Unit Testing is writing small test units of code. Unit Testing - Wikipedia

You are on the right track, for the most part, overlaying FileReader, etc. before calling the jump function. This is a very good way to test code that relies on another external library / function / framework. The corresponding part of the Wikipedia page for Unit Testing states

Since some classes may have references to other classes, class testing can often flow into testing of another class. Classes that depend on the database are a common example of this: for testing a class, the tester often writes code that interacts with the database. This is a mistake because unit test usually does not go beyond the class’s own boundary and especially should not cross such process / network boundaries because it can lead to unacceptable performance problems for unit test -suite.

Here, however, when you create your dummy FileReader or scoff at it, it never calls "onloadend" because mock / stub does not have this system of events and events. This means that the layout is incomplete on your part. Wikipedia countries

Instead, the software developer should create an abstract interface around the database queries, and then implement this interface with his own mock object. By exhausting this necessary investment from the code (temporarily reducing the net effective connection)

In your case, and not in the database, you will mock the FileReader file event.

In a test run, your current code needs a small refactor to become testable. The overall goal of Unit Tests is to test small units of functionality in isolation.

The purpose of unit testing is to isolate the unit and verify its correctness.

The jump function is based on the nested arrow function associated with onloadend. Your code has a direct challenge to the one that was commented on in the test, I'm a little surprised that I didn’t work on your code to be honest, and would suggest, perhaps, to make sure that your code coverage tool, perhaps Istanbul, if you are with Using Jasmine is configured correctly.

Based on the foregoing, you should reorganize this nested function and instead create a named function that you can then call directly for your unit tests.

This (unverified at my end) is an example of a better way to implement your function.

 jumping(inputValue: any): void { var that = this; var file: File = inputValue.files[0]; var seat: FileReader = new FileReader(); // bind the arguments for the event handler, first arg will be 'this' of the // loaded named function // second is 'that' variable, seat is seat and the final 'e' variable is // implicit and shouldn't be specified. seat.onloadend = loaded.bind(seat, that, seat); $('.running').show(); if (inputValue.files.length > 0) { var wholeQuantity = 0; wholeQuantity = inputValue.files[0].size / 1048576; //size in mb if (wholeQuantity > 5) { $('.stars').show(); $("#laptop").val(''); this.fileSelect = ""; } seat.readAsDataURL(file); } } loaded(that: any, seat: any, e: any): void { // now a testable named function this.encodeBase64 = seat.result; that.fileSelect = $("#laptop").val().replace(/^.*\\/, ""); if (that.fileSelect == '') { that.dragDrop = that.swimming; } else { that.dragDrop = ""; that.dragDrop = that.fileSelect; } } 

An example of a test that will cover all lines of code of a “loaded” function, as described above, is as follows:

 describe('test suite', function () { var old$ = $; afterEach(function () { $ = old$; }); it('covers all lines and else path on if but does not actually test anything', function () { $ = function () { val: function () { return 'Untitled-2.txt'; } }; // stub JQuery var seat = { result: 'Base64encoded' }; var scope = {}; var that = { swimming: false, dragDrop: null }; BasketballChainComponent.kickmobiles.loaded.call(scope, that, seat, null); }); it('covers all lines and on if but not else and does not actually test anything', function () { $ = function () { val: function () { return ''; } }; // stub JQuery var seat = { result: 'Base64encoded' }; var scope = {}; var that = { swimming: false, dragDrop: null }; BasketballChainComponent.kickmobiles.loaded.call(scope, that, seat, null); }); 

});

Now, please note: in the real world, you should never write tests just to cover code that does not actually test these functions. This will lead you into a false sense of security, and not actually TEST your code. MSDN says the following:

The main goal of unit testing is to take the least amount of software under test into the application, isolate it from the rest of the code and determine whether it will behave exactly as you expect.

The analogy of what you are doing will be as follows:

You work as a car accident tester. Your task is to make sure that the car is safe. Thus, the car crashed at a speed of 10 km / h, and you need to check it.

You take a checklist of things to confirm. Thus, when you crash at 10 km / h, you expect the paint to be scratched. So you look at the paint, if the paint is scratched, but there is no other damage, the test passes. If the car is dented, the test will fail.

This is a good test overall, as it tests something quantifiable and tests intent.

What you do when trying to achieve 100% code coverage without actually checking the functionality is a car crash and then not checking anything.

You say: "Well, I crashed the car, I really do not need to check that she did what she had to do in the accident while I collapsed?".

Of course, you have a 100% crash coverage while looking at the car, but without actually testing it, you can not even worry. Code coverage is a useful tool for defining code that has not been tested; it is not used to achieve an arbitrary metric for obtaining full code coverage. Further reading of this and excellent recording can be read on the Broken promise of 100% code coverage

In essence, its essence is

The fact that code coverage is easy to measure does not make it a good indicator. You can get in trouble even if your code coverage is 100%.

I omitted the code from the article in the environment, but it continues to indicate:

This unit test provides the perfect 100% coverage for the elementAtIndex: function. Does this prove that the function is working correctly? The answer is obviously no. What happens when we exceed the boundaries of an array? Why did this happen? When you try to focus on the metric of code coverage, you write code that considers the implementation of a proven function / method. But the implementation has not yet been proven. It is for this reason that we want to test it. Even so, simply covering the function code failed as a good metric for measuring the quality of unit tests.

Further, above, I declare that you must verify the intent of your code. The Medium article also talks about this.

What to do? Do not look at the actual implementation of the method, look at the contract. Look exactly at the function / method outputs for any particular inputs. Look at the side effects that this function performs or uses. Consider possible extreme cases that may exist. List this information and run the tests accordingly.

Remembering 100% code coverage does not mean that your code is 100% correct.

Hope this helps you understand Unit Testing as a concept a little better.

+7
source

Source: https://habr.com/ru/post/1271458/


All Articles