Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
How do I run a test case in Angular 6 Jasmine-Karma on a method that calls subscribe and returns data from an API?

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()?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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);
});
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda