|
| 1 | +import { describe, expect, test } from 'vitest'; |
| 2 | +import { asyncNotifier } from '../../src/utils/async'; |
| 3 | + |
| 4 | +describe('notifyIterator', () => { |
| 5 | + const neverAbort = new AbortController().signal; |
| 6 | + |
| 7 | + test('waits for event', async () => { |
| 8 | + const notifier = asyncNotifier(); |
| 9 | + let didReceiveEvent = false; |
| 10 | + notifier.waitForNotification(neverAbort).then((e) => { |
| 11 | + didReceiveEvent = true; |
| 12 | + }); |
| 13 | + |
| 14 | + await Promise.resolve(); |
| 15 | + expect(didReceiveEvent).toBeFalsy(); |
| 16 | + notifier.notify(); |
| 17 | + |
| 18 | + await Promise.resolve(); |
| 19 | + expect(didReceiveEvent).toBeTruthy(); |
| 20 | + }); |
| 21 | + |
| 22 | + test('merges events', async () => { |
| 23 | + const notifier = asyncNotifier(); |
| 24 | + for (let i = 0; i < 1000; i++) { |
| 25 | + notifier.notify(); |
| 26 | + } |
| 27 | + |
| 28 | + let didReceiveEvent = false; |
| 29 | + notifier.waitForNotification(neverAbort).then((e) => { |
| 30 | + didReceiveEvent = true; |
| 31 | + }); |
| 32 | + await Promise.resolve(); |
| 33 | + expect(didReceiveEvent).toBeTruthy(); |
| 34 | + |
| 35 | + // The first iterator.next() should have consumed everything. |
| 36 | + didReceiveEvent = false; |
| 37 | + notifier.waitForNotification(neverAbort).then((e) => { |
| 38 | + didReceiveEvent = true; |
| 39 | + }); |
| 40 | + await Promise.resolve(); |
| 41 | + expect(didReceiveEvent).toBeFalsy(); |
| 42 | + }); |
| 43 | + |
| 44 | + test('completes on abort', async () => { |
| 45 | + const notifier = asyncNotifier(); |
| 46 | + await notifier.waitForNotification(AbortSignal.abort()); |
| 47 | + }); |
| 48 | + |
| 49 | + test('completes on abort later', async () => { |
| 50 | + const notifier = asyncNotifier(); |
| 51 | + await notifier.waitForNotification(AbortSignal.timeout(10)); |
| 52 | + }); |
| 53 | +}); |
0 commit comments