Divyanshu Jimmy
Divyanshu Jimmy

Reputation: 2752

Not able to cover ngOnInit() in jasmine test case

I am new to Jasmine for Angular 5.

I am trying to write a test case but in my coverage report I am always getting ngOnInit()t() not covered : enter image description here

following is mine spec file, I am passing null to Constructor of my component but in actually it needs a service :

  let component: LoginPageHeaderComponent;
          let fixture: ComponentFixture<LoginPageHeaderComponent>;

          beforeEach(async(() => {
            TestBed.configureTestingModule({
              declarations: [ LoginPageHeaderComponent ],
              providers: [ ServerBindingService  ],
              imports: [ HttpClientTestingModule]
            })
            .compileComponents();

            component = new LoginPageHeaderComponent(null);
          }));
          it('Should initialize all variables ', async(() => {

     component.ngOnInit();
            const a = component.isNetworkCallFinsihed;
            const b = component.allLeftHeaderOptions$;
            const c = component.allRightHeaderOptions$;
            component.ngOnInit();
            fixture.detectChanges();
            expect (a).toBeTruthy() ;
          }));

Please let me know what I am missing and I should add here .

edit

Adding Component

import { ServerBindingService } from './../server-binding.service';
import { Component, OnInit, NgModule   } from '@angular/core';
import { Observable } from 'rxjs/Observable';

@NgModule({
})

@Component({
  selector: 'app-login-page-header',
  templateUrl: './login-page-header.component.html',
  styleUrls: ['./login-page-header.component.css']
})
export class LoginPageHeaderComponent implements OnInit {

  allLeftHeaderOptions$: Observable<any>;
  allRightHeaderOptions$: Observable<any>;
  isNetworkCallFinsihed: Observable<boolean>;
  constructor(private serverBindingService: ServerBindingService) { }

  ngOnInit() {
    console.log('called');
    this.allLeftHeaderOptions$ = this.serverBindingService.leftHeaderLinks$;
    this.allRightHeaderOptions$ = this.serverBindingService.rightHeaderLinks$;
    this.isNetworkCallFinsihed = this.serverBindingService.isNetworkCallFinished$;
  }

} 

Solution I was using fdescribe on my other test case because of this my current test case was not running. Noob error!

Upvotes: 0

Views: 3264

Answers (1)

Antoniossss
Antoniossss

Reputation: 32535

You have to call ngOnInit() manually as there is no lifecycle during test. That is intentional.

No lifecycle = No lifecycle hook methods invoked. ngOnInit is one of them.

Upvotes: 4

Related Questions