簡體   English   中英

如何在Jasmine中使用CombineLatest為方法提供可觀察的Rxjs數據

[英]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 可能原因:

  1. 我將數據提供給Observable.of
  2. 我用錯誤的方式創建了一個可觀察的對象(我不應該使用observable.of)。
  3. 我需要調用一個發射器,以便將可觀察到的數據傳遞給CombineLatest。
  4. 我沒有發現的原因

任何建議,不勝感激。 謝謝。

我認為您的代碼中存在多個問題。

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),
];

combineLatest

請參閱散布算子的文檔

connect() {
    return combineLatest(...this.value).pipe(
        map(...data) => {
            return data[this.key]
        }
    );
  }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM