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.
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.
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.
The tick() function simulates the asynchronous passage of time for the timers in the fakeAsync zone in Angular test.
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.
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') }))
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With