25

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.

stijn.aerts
  • 6,026
  • 5
  • 30
  • 46

1 Answers1

25

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')
}))
Oleg Barinov
  • 1,635
  • 12
  • 7
  • 1
    my ngOnInit calls a http.get (via service method) and upon its return, sets the data to the received value. If I wrap the testing code in a setTimeout, it succeeds but the tick method doesn't seem to work (even when provided a timeout same as the setTimeout value.. Not sure why – NitinSingh Feb 01 '18 at 10:09