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

155
Visualizações
Angular2 Component Unit Testing with Service Dependency

So I have this PromptComponent and the content will be updated by a service data. Now I am trying to do the unit test this component which has this service dependency. Here is the Component:

export class PromptComponent {
    @Input() module: any;
    @select() selectedPrompt;
    constructor(private moduleService: ModuleService){}
}

Here is the service:

  getQuote(): Promise<string> {
    return new Promise(resolve => {
      setTimeout( () => resolve(this.nextQuote()), 500 );
    });
  }
  private nextQuote() {
    if (this.next === quotes.length) { this.next = 0; }
    return quotes[ this.next++ ];
  }

Here is the unit test code:

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [
        PromptComponent,
      ],
      providers: [ ModuleService]
    });

    fixture = TestBed.createComponent(PromptComponent);
    component = fixture.componentInstance;
    const moduleService = fixture.debugElement.injector.get(ModuleService);
    spy = spyOn(moduleService, 'getQuote').and.returnValue(Promise.resolve(testService));  

I referred to the official demo on the angular documentation https://angular.io/resources/live-examples/testing/ts/eplnkr.html, as inside the TwainComponent.spec.

Something really weird is that as expected, inside the official demo, the TwainComponent test passed smoothly. But I, on the other hand, got this strange injectionError. If I remove the parameter inside the constructor, I am able to create the fixture instance but get injection error when it runs thorught the injector.get() part. But as soon as I put the private moduleService:ModuleService back inside the component constructor, I will get fixture undefined and also with the injection error.

So that means I cannot even execute my code to the actual service injection part (fixture.debugElement.injector.get(ModuleService)), I already got the error.

Does anybody have the same issue? My code is almost identical to the demo code on Plunker. Have no clue how to move forward....

over 4 years ago · Santiago Trujillo
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