簡體   English   中英

測試可觀察到的RxJS是否跟蹤最后發出的值(沒有完整的信號)?

[英]Testing RxJS observable that tracks the last emitted value (no complete signal)?

我做了一些搜索,但是找不到我的用例的簡單答案。 如果在SO上已經存在足夠類似的問題,我預先表示歉意。

我有一個可觀察的myObservable ,它不斷地從商店流式傳輸一個值(即,它代表商店的狀態)。 我想用Jest測試一下,當商店發生更改時,我的Observable是否能夠正確更新。

// i.e. every time the value changes, an event is emitted by myObservable
myObservable.subscribe(x => console.log(x))

因此,我真正想要做的是如下所示:

await myStore.set(0)
// insert here: check that `myObservable` stream is a 0
await myStore.set(5)
// insert here: check that `myObservable` stream is a 5

基本上,我需要一種在任何時間點“輕敲” myObservable ,以查看最后一次發出的值。 抱歉,這是一個n00b問題。

我不確定這是否有效。 但是您可以嘗試一下。

這段代碼在Jasmine中,我希望在Jest中會有些相似。

fit('Should test observable with store', fakeAsync(() => {
  const testData = [1, 2, 3, 4];
  let index = 0;

  myObservable.subscribe(t => {
    expect(t).toBe(testData[index]);
  });

  testData.forEach(td => {
    myStore.set(td)
    tick(100);
    index++;
  });
}));

該解決方案創建一個訂閱以接收期望值,執行斷言並結束測試。

盡管時間略長,但對我來說似乎很慣用,並且應該能夠隨着應用程序的響應需求增長而擴展。

import { from, Observable, of } from 'rxjs'
import { concatMap, finalize, take, tap, toArray } from 'rxjs/operators'

// sample "definitions" to make the example compile
// replace "myObservable", "myStore" with actual code for expected result
const myObservable: Observable<number> = of(123)
const myStore: {
  set: (number) => Promise
} = null as any

describe('my test', () => {
  it('is an example', done => {
    // configure observable to assert emitted values
    myObservable.pipe(
      // this subscription will complete after emitting 2 values
      take(2),
      // put all the values into a single array
      toArray(),
      // assert the values (that has been converted to array)
      tap(vals => expect(vals).toBe([0, 5]),
      // this will ensure the test does not 'hang' on observable error
      finalize(() => {
        // test will fail if assertion did not happen
        expect.assertions(1)
        done()
      })
    ).subscribe()

    // --- pick preferred way to execute - "set store value"
    // option 1: set 0 then set 5 (using observables)
    from(myStore.set(0)).pipe(
      concatMap(() => myStore.set(5))
    ).subscribe()

    // option 2: set 0 then set 5 (using promises)
    myStore.set(0).then(() =>
      myStore.set(5)
    )
  })
})

祝好運!

暫無
暫無

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

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