Swarup
Swarup

Reputation: 57

check if inner method is being called in angular jasmine test case

I'm learning to write test cases using jasmine for my angular application,stuck in a particular scenario I have a function inside a component that calls other private function/methods the function is as below

 public rPage() {
    this.setData(); // private method 
    this.setPage(); // private method
  }

I wrote the test case to test it as below

 it('should call setData from RPage', () => {
    //@ts-ignore
    const spy = spyOn(component, 'setData');
    component.rPage();
    fixture.detectChanges();
    expect(spy).toHaveBeenCalled();
  });

but when i run ng test the test case fails and says 'Expected spy setData to have been called. what changes should I implement to pass the test case

Upvotes: 2

Views: 2609

Answers (1)

Lin Du
Lin Du

Reputation: 102672

It should work.

E.g.

example.component.ts:

import { Component } from '@angular/core';

@Component({})
export class ExampleComponent {
  public rPage() {
    this.setData();
    this.setPage();
  }
  private setData() {}
  private setPage() {}
}

example.component.spec.ts:

import { ExampleComponent } from './example.component';

fdescribe('64929369', () => {
  it('should call setData from RPage', () => {
    const component = new ExampleComponent();
    //@ts-ignore
    const setDataSpy = spyOn(component, 'setData');
    //@ts-ignore
    const setPageSpy = spyOn(component, 'setPage');
    component.rPage();
    expect(setDataSpy).toHaveBeenCalled();
    expect(setPageSpy).toHaveBeenCalled();
  });
});

test result: enter image description here

Upvotes: 2

Related Questions