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

152
Vistas
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 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