UNPKG

1.43 kBPlain TextView Raw
1import { Scheduler } from 'rxjs';
2
3let requestQueue = [];
4let timeElapsed: number = 0;
5
6import { fakeAsync as ngFakeAsync, flushMicrotasks, tick as ngTick } from '@angular/core/testing';
7export { flushMicrotasks };
8
9/**
10 * Wraps angular fakeAsync with the ability to track pending requests
11 *
12 * When a request is initiated using mockAsync, the request is pushed to the requestQueue
13 * If there are any pending requests at the end of the function, an exception will be thrown.
14 *
15 * Also overrides 'now' on the default rxjs scheduler to return a value based on how much time has elapsed via 'tick'
16 *
17 * @param fn
18 * @returns {Function} The function wrapped to be executed in the fakeAsync zone
19 */
20export function rlFakeAsync(fn: Function): { (done?: { (): void }): void } {
21 return ngFakeAsync(function (...args) {
22 const originalNow = Scheduler.async.now;
23 timeElapsed = 0;
24 Scheduler.async.now = () => timeElapsed;
25 requestQueue = [];
26 let res = fn(...args);
27 flushMicrotasks();
28 if (requestQueue.some(request => request.pending)) {
29 throw new Error('There are still pending requests. Please be sure to flush all of your requests');
30 }
31 Scheduler.async.now = originalNow;
32 return res;
33 });
34}
35
36export function rlQueueRequest(request): void {
37 requestQueue.push(request);
38}
39
40export function rlTick(milliseconds: number) {
41 timeElapsed += milliseconds;
42 ngTick(milliseconds);
43}