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.
- 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 { }
- 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);
}
}
- 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;
}
}
- 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();
}));
});