This is my ts file, where I'm calling the method from ngOnInit, and getAllAccounts is where I'm fetching the API
ngOnInit(): void {
this.getAllAccounts();
}
getAllAccounts() {
this.service.getAllAccounts().subscribe({
next: (data: any) => {
if (data) {
this.allAccounts = data;
}
},
});
}
This is my spec file where I'm trying to test the data being rendered
it("should test subscribe method is getting called", fakeAsync(() => {
const accountSpy = spyOn(service, "getAllAccounts").and.returnValue(of(getAllAccountsList()));
const subSpy = spyOn(service.getAllAccounts(), "subscribe");
component.ngOnInit();
tick(100);
expect(accountSpy).toHaveBeenCalled();
tick(300);
expect(subSpy).toHaveBeenCalled();
}));
it("should test execution within subscribe method", fakeAsync(() => {
component.ngOnInit();
expect(component.allAccounts).toBeDefined();
expect(component.allAccounts.length).toBeGreaterThan(5);
}));
Also, how do I test ngOnInit()?
The first fixture.detectChanges() you call is when ngOnInit is called. That being said, it is no problem calling ngOnInit manually in a unit test. To test what you have, I would do:
it('should set allAccounts', () => {
// spy on the service method and return an observable
spyOn(service, "getAllAccounts").and.returnValue(of(getAllAccountsList()));
component.ngOnInit();
// assert that their lengths are the same
expect(component.allAccounts.length).toBe(getAllAcountsList().length);
});