如果我使用@Inject方法创建一个带有服务的模块,则不能使用Angular 2 Testbed Unit测试用例。它没有为AppService错误提供任何提供程序。
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 { }
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);
}
}
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;
}
}
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();
}));
});
答案 0 :(得分:0)
尝试在app.component.ts中的@Component中添加提供者:[AppService],如下所示
@Component({
providers: [AppService],
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})