当我在一个组件中使用以下服务时,显示错误 "TypeError: Cannot read property 'next' of undefined",并且之前没有引起任何问题的测试也失败了。
服务。
export class DataService {
loadData$: Observable<string>;
observerLoadData: Observer<string>;
constructor() {
this.loadData$ = new Observable(observer => this.observerLoadData = observer);
this.startObs();
}
startObs() {
setTimeout(() => {
this.observerLoadData.next('LOADEDDATA$');
console.log('huhu');
}, 2500); }
}
Component:
....
constructor(private dataService: DataService) {
this.dataService.loadData$.subscribe(value => this.loadedData = value);
}
....
SpecTs。
....
beforeEach(async(() => {
TestBed.configureTestingModule({
declarations: [
AppComponent
],
providers: []
,
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
]
}).compileComponents().then(() => {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
de = fixture.debugElement.query( By.css('form') );
el = de.nativeElement;
});
....
你需要将 DataService
在测试中也。
providers: [
{
provide: DataService,
useValue: {
loadData$: of('VALUE_OF_LOADED_DATA'),
},
},
],