Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

118
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda