Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Wait for ngOnInit to finish in Jasmine Angular2

Tags:

I'm unit testing a component and this is what I have:

describe('Component: nav', () => {    beforeEach(() => addProviders([     provide(UserService, {useClass: MockUserService}),     NavComponent   ]));    it('should have a property \'firstName\' with the value \'Crazypug\'',     async(inject([NavComponent], (component) => {       component.ngOnInit();       expect(component.firstName).toEqual('Crazypug')     }))   );  }); 

This is the ngOnInit function:

ngOnInit() {     this.userService.getFirstNameCall().subscribe(       data => {this.firstName = data.firstname; }); } 

When I run the test I get:

Expected undefined to equal 'Crazypug'

How can I let Jasmine wait for the ngOnInit function to finish? I found some solutions on SO but from a long time ago (in angular2 terms of time). They were very complicated or outdated.

like image 954
stijn.aerts Avatar asked Jul 15 '16 08:07

stijn.aerts


People also ask

What is done () in Jasmine?

If the function passed to Jasmine takes an argument (traditionally called done ), Jasmine will pass a function to be invoked when asynchronous work has been completed.

Does fixture detectChanges call ngOnInit?

fixture. detectChanges() tells Angular to run change-detection. Finally! Every time it is called, it updates data bindings like ng-if, and re-renders the component based on the updated data. Calling this function will cause ngOnInit to run only the first time it is called.

What is tick () in Angular?

The tick() function simulates the asynchronous passage of time for the timers in the fakeAsync zone in Angular test.

What is the difference between async ()' and fakeAsync ()'?

tl;dr. In almost all cases, they can be used interchangeably, but using fakeAsync()/tick() combo is preferred unless you need to make an XHR call, in which case you MUST use async()/whenStable() combo, as fakeAsync() does not support XHR calls. For the most part they can be used interchangeably.


1 Answers

You should replace async function for fakeAsync

import {..., tick, fakeAsync} from '@angular/core/testing'; ... fakeAsync(inject([NavComponent], (component) => {   component.ngOnInit();   tick();   expect(component.firstName).toEqual('Crazypug') })) 
like image 174
Oleg Barinov Avatar answered Oct 13 '22 19:10

Oleg Barinov