0

If I create a module with services using @Inject method is not working with Angular 2 Testbed Unit test cases. It is throwing No Provider for AppService Error.

  1. app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';

import { AppComponent } from './app.component';
import { AppService } from './app.service';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [
    {provide:'AppService',useClass:AppService}
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }
  1. app.component.ts

import { Component, Inject } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'app works!';

  constructor(@Inject('AppService') private appService) {}

  getName() {
    this.title = this.appService.getName();
  }

  setName(name) {
    this.appService.setName(name);
  }
}
  1. app.service.ts

import { Injectable } from '@angular/core';

@Injectable()
export class AppService {
  private name = 'dummy';

  public getName() {
    return this.name;
  }

  public setName(name) {
    console.log("ser", name);
    this.name = name;
  }
}
  1. app.component.spec.ts

import { Injectable} from '@angular/core';
import { TestBed, async, inject } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';

import { AppService } from './app.service';


describe('AppComponent', () => {

  let fixture, comp, appService;

  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [FormsModule],
      declarations: [
        AppComponent
      ],
      providers: [AppService]
    }).compileComponents();

    fixture = TestBed.createComponent(AppComponent);
    comp = fixture.debugElement.componentInstance;
    appService = fixture.debugElement.injector.get(AppService);
  });



  it('should create the app', async(() => {
    expect(comp).toBeTruthy();
  }));

});
Dinesh
  • 426
  • 5
  • 15

1 Answers1

0

try adding providers: [AppService] in @Component in app.component.ts as below

@Component({
providers: [AppService],
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
  • If we directly give provider, that is working. But I wanted to use **@Inject** decorator in component. If we use directly 'AppService', we have to import it to component. Instead if we use **@Inject** method, we can import it in module level and use it all components with @Inject – Dinesh Mar 31 '17 at 10:42