[英]How to supply an Rxjs observable as data for a method using combineLatest in Jasmine
我目前有一個combineLatest
方法,該方法通過我的課程提供:
export class ObservableDataSource extends DataSource<any> {
private value: any[];
private key: string;
constructor(value: any[], key) {
super();
this.value = value;
this.key = key;
}
connect() {
//Code related to question starts here
return combineLatest(this.value, (data) => {
return data[this.key];
});
//Code related to question ends here
}
disconnect() {}
}
在單元測試中,我有一個beforeEach,用於實例化組件並提供一個可觀察的對象:
const dummyData = [{
visible: {
data: 'test123'
}
}];
const observableDummyData = Observable.of([dummyData]);
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{provide: ObservableDataSource, useValue: new ObservableDataSource(observableDummyData, 'visible')}
]
});
});
it('should be created', inject([ObservableDataSource], (service: ObservableDataSource) => {
expect(service).toBeTruthy();
}));
唯一的問題是,當在控制台中查看業力運行程序時,雖然this.value顯示為可觀察的,但從CombineLatest發出的數據顯示為空的TypeError: Cannot read property 'visible' of undefined
。 可能原因:
Observable.of
任何建議,不勝感激。 謝謝。
我認為您的代碼中存在多個問題。
1.您的服務期望其value
參數為數組,但是您正在提供一個簡單的Observable。
2 combineLatest
可用於多個可觀察參數,而不是參數數組。
return combineLatest(obsA, obsB, obsC, (a, b, c) => { ... });
// or with the spreading operator
return combineLatest(...arrayOfObs).map((...data) => { ... });
const dummyData1 = [{
visible: {
data: 'test123'
}
}];
const dummyData2 = [{
visible: {
data: 'somethingElse'
}
}];
const observableDummyData = [
Observable.of(dummyData1),
Observable.of(dummyData2),
];
請參閱散布算子的文檔
connect() {
return combineLatest(...this.value).pipe(
map(...data) => {
return data[this.key]
}
);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.