Este es mi archivo ts, donde llamo al método desde ngOnInit, y getAllAccounts es donde busco la API
ngOnInit(): void { this.getAllAccounts(); } getAllAccounts() { this.service.getAllAccounts().subscribe({ next: (data: any) => { if (data) { this.allAccounts = data; } }, }); }Este es mi archivo de especificaciones en el que intento probar los datos que se procesan
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); }));Además, ¿cómo pruebo ngOnInit()?
El primer fixture.detectChanges() al que llama es cuando se llama a ngOnInit . Dicho esto, no hay problema en llamar a ngOnInit manualmente en una prueba unitaria. Para probar lo que tienes, yo haría:
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); });