Type Error: Cannot read property 'next' of undefined in Angular/Jasmine
Type Error: Cannot read property 'next' of undefined in Angular/Jasmine
当我在组件中使用以下服务时,显示错误"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); }
}
组件:
....
constructor(private dataService: DataService) {
this.dataService.loadData$.subscribe(value => this.loadedData = value);
}
....
规格:
....
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'),
},
},
],
当我在组件中使用以下服务时,显示错误"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); }
}
组件:
....
constructor(private dataService: DataService) {
this.dataService.loadData$.subscribe(value => this.loadedData = value);
}
....
规格:
....
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'),
},
},
],