Angular testing if component method is called during ngOninit?

4k views Asked by At

My goal is to create spys of certain methods and check that the methods were called during ngOninit and if pagePurpose equals Update. Currently Im trying to setup the spys and set the component property in the describe and then trying to assert if the functions were called but I get : Expected spy createLineReviewRequest to have been called. I feel like Im creating the spys but not using them properly. I need to do this with the highlight method as well, notice that for my case I dont care what the methods were passed.

My Component is as follows :

export class ReportsModalLineReviewComponent implements OnInit {
  
  pagePurpose: string;
  canContinue: boolean ;

  constructor() { }

  ngOnInit() {
   
    if (this.pagePurpose === "Update" ) {
      this.highlight(this.dialogData.oldReport.lineReviewRequest.lineReviewFile.fileId)
      this.createLineReviewRequest(this.dialogData.oldReport.lineReviewRequest.lineReviewFile);
      this.canContinue = true;
    }
  }

Mt Test is as follows :

beforeEach(() => {
    fixture = TestBed.createComponent(ReportsModalLineReviewComponent);
    component = fixture.componentInstance;

    component.pagePurpose = "Update";
    spyOn(component, 'createLineReviewRequest');

    fixture.detectChanges();
 });

fit('should check if Update', () => {
    
    expect(component.createLineReviewRequest).toHaveBeenCalled();
  });

Would really appreciate the help!

2

There are 2 answers

2
Luis Reinoso On

The onInit needs to be called manually

I suggest to follow a convention to make unit testing. GIVEN -> WHEN -> THEN

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

beforeEach(async(() => {
  TestBed.configureTestingModule({
    imports: [CommonModule],
    declarations: [ReportsModalLineReviewComponent]
  }).compileComponents();
}));

beforeEach(() => {
    fixture = TestBed.createComponent(ReportsModalLineReviewComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
 });

fit('should check if Update', () => {
    // GIVEN
    component.pagePurpose = "Update";
    spyOn(component, 'createLineReviewRequest');

    // WHEN
    component.ngOnInit()

    // THEN
    expect(component.createLineReviewRequest).toHaveBeenCalled();
});
0
kaan bobac On

In case somebody might encounter this issue:

Error: : Expected a spy, but got Function.

In order to solve it, I changed

This:

  component.ngOnInit();
  expect(component.someMethod).toHaveBeenCalled();

To This:

const spy = spyOn(component,'someMethod');
component.ngOnInit();
expect(spy).toHaveBeenCalled();