Vishal Hasnani
Vishal Hasnani

Reputation: 728

Angular 7: ngOnInit() of the a component is getting called every time running unit test case of that component

I'm creating unit test cases for angular 7 component. I'm having a component which contains ngOnInit() to call getUser data function of that component.

Component file:

ngOnInit() {
    this.getUserDetails(); // If commented test runs successfully
  }


  getUserDetails() {
    this.guestUserService.getData().subscribe(
      result => {
        this.profileForm = this.fb.group({
          firstName: [result['data']['firstname'], Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z ]+$')])],
          lastName: [result['data']['lastname'], Validators.compose([Validators.required, Validators.pattern('^[a-zA-Z ]+$')])],
          username: [{ value: result['data']['username'], disabled: true }, Validators.compose([Validators.required, Validators.email])]
        });
        this.imageURL = result['data']['imageFile'];
      }
    );
  }

Created the unit test case for the function getUserDetails()

let guestUserService: any;
let guestUserServiceSpy: any;

TestBed.configureTestingModule({ 
providers: [
        { provide: GuestUserService, useValue: guestUserService }]
    })

it('should get user data and create profile form when getUserDetails called', () => {
    guestUserServiceSpy = guestUserService.getData.and.returnValue(of({
      data: { firstname: 'ABC', lastname: 'XYZ', username: 'ABC@XYZ', imageFile: 'http://imagefile.XYZ.com' }
    }
    ));

    spyOn(component, 'getUserDetails').and.callThrough();
    component.getUserDetails();
    fixture.detectChanges();
    expect(guestUserService).toBeDefined();
    expect(guestUserServiceSpy).toBeDefined();
    expect(component.getUserDetails).toHaveBeenCalledTimes(1);
    expect(guestUserServiceSpy).toHaveBeenCalledTimes(1);
    expect(component.profileForm.valid).toBeTruthy();
    expect(component.profileForm.controls['username'].value).toEqual('ABC@XYZ');
  });

While runnning ng test to run this test case, component's ngOnInit is getting called first and giving the error:

TypeError: Cannot read property 'subscribe' of undefined Expected spy GuestUserService.getData to have been called once. It was called 2 times.

If i remove the call to function "getUserDetails()" the test case run successfully.

Any better solution to handle this kind of behaviour Or I'm missing something. enter image description here

Upvotes: 1

Views: 4319

Answers (1)

Jun Ee
Jun Ee

Reputation: 301

It called twice because you have component.getUserDetails() and fixture.detectChanges() in the test case.

fixture.detectChanges() will trigger ngOnInit() and you already have getUserDetails() in the method.

Upvotes: 3

Related Questions