Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

151
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!