how to use the virtualaction function from the rxjs library in typescript

The virtualAction function is used for simulating time progression in RxJS. It is often used in unit testing of observables.

Here is an example of using virtualAction in TypeScript:

index.ts
import { TestScheduler, virtualAction } from 'rxjs';

describe('myObservable', () => {
  let scheduler: TestScheduler;

  beforeEach(() => {
    scheduler = new TestScheduler((actual, expected) => {
      expect(actual).toEqual(expected);
    });
  });

  it('should work with virtual time', () => {
    scheduler.run(({ cold, expectObservable }) => {
      const source$ = cold('a-b-c|');
      const expectedValues = { a: 1, b: 2, c: 3 };

      expectObservable(source$.pipe(
        map(val => val.charCodeAt(0) - 96)
      )).toBe('x-y-z|', expectedValues);

      scheduler.schedule(virtualAction(() => {
        expectObservable(source$.pipe(
          map(val => val.charCodeAt(0) - 96)
        )).toBe('w-x-y-z|', expectedValues);
      }, 50));

      expectObservable(source$.pipe(
        map(val => val.charCodeAt(0) - 96)
      )).toBe('a-b-c|', expectedValues);
    });
  });
});
895 chars
33 lines

In this example, we create a TestScheduler instance and use its run method to simulate time progression. Inside the run method, we create a cold observable source$ which emits three values 'a', 'b', and 'c'.

We then use the expectObservable method to assert that our observable emits the expected values.

Next, we use the scheduler.schedule method to schedule a virtual action which will be executed after 50 virtual time units. Inside the virtual action, we again use expectObservable to assert that our observable emits the expected values.

Finally, we use expectObservable again outside the virtual action to assert that our observable still emits the expected values.

By using the virtualAction function and the TestScheduler, we can simulate time progression and test observables in a deterministic and repeatable way.

gistlibby LogSnag