Member-only story

RxJS: Testing with Fake Time

Nicholas Jamieson
3 min readJun 27, 2018

--

Photo by rawpixel on Unsplash

Angular, Jasmine, Jest and Sinon.JS all provide APIs for running tests with fake time. Their APIs differ, but they are broadly similar:

  • Before each test, time-related functions like setTimeout and setInterval are patched to use fake time instead of actual time.
  • Within a test, an API call can be made to advance the clock by a specified number of fake milliseconds.
  • After each test, the patched functions are restored.

Running tests with fake time avoids having to wait for actual time to elapse and it also makes the tests much simpler, as they run synchronously.

So what does this have to do with RxJS?

RxJS has its own concept of fake time — which is named virtual time. In RxJS, all time-related functionality is implemented in schedulers and there is a particular scheduler for virtual time: the VirtualTimeScheduler.

To test RxJS-based code with virtual time, any schedulers used — either explicitly or implicitly — need to be swapped for an instance of the VirtualTimeScheduler.

Unfortunately, that’s not always easy to do. And using the VirtualTimeScheduler won’t help if the code under test also includes time-related, non-RxJS code, as the virtual and fake time concepts differ significantly.

--

--

Nicholas Jamieson
Nicholas Jamieson

Written by Nicholas Jamieson

RxJS core team member; front-end developer; mentor; speaker; open-source contributor

Responses (1)