|
| 1 | +import * as events from 'node:events'; |
| 2 | +import { timeout } from '../time'; |
| 3 | + |
| 4 | +describe('Helper tests', () => { |
| 5 | + test('timeout function should not cause memory leak by accumulating abort listeners on abort', async () => { |
| 6 | + const controller = new AbortController(); |
| 7 | + const { signal } = controller; |
| 8 | + |
| 9 | + const countListeners = () => events.getEventListeners(signal, 'abort').length; |
| 10 | + |
| 11 | + // Ensure the initial listener count is zero |
| 12 | + expect(countListeners()).toBe(0); |
| 13 | + |
| 14 | + // Run enough iterations to detect a pattern |
| 15 | + for (let i = 0; i < 100; i++) { |
| 16 | + try { |
| 17 | + const sleepPromise = timeout(1000, signal); |
| 18 | + controller.abort(); // Abort immediately |
| 19 | + await sleepPromise; |
| 20 | + } catch (err: any) { |
| 21 | + expect(err.toString()).toMatch(/aborted/i); |
| 22 | + } |
| 23 | + |
| 24 | + // Assert that listener count does not increase |
| 25 | + expect(countListeners()).toBeLessThanOrEqual(1); // 1 listener may temporarily be added and removed |
| 26 | + } |
| 27 | + |
| 28 | + // Final check to confirm listeners are cleaned up |
| 29 | + expect(countListeners()).toBe(0); |
| 30 | + }); |
| 31 | + |
| 32 | + test('timeout function should not cause memory leak by accumulating abort listeners on successful completion', async () => { |
| 33 | + const controller = new AbortController(); |
| 34 | + const { signal } = controller; |
| 35 | + |
| 36 | + const countListeners = () => events.getEventListeners(signal, 'abort').length; |
| 37 | + |
| 38 | + // Ensure the initial listener count is zero |
| 39 | + expect(countListeners()).toBe(0); |
| 40 | + |
| 41 | + // Run enough iterations to detect a pattern |
| 42 | + for (let i = 0; i < 100; i++) { |
| 43 | + await timeout(2, signal); // Complete sleep without abort |
| 44 | + |
| 45 | + // Assert that listener count does not increase |
| 46 | + expect(countListeners()).toBe(0); // No listeners should remain after successful sleep completion |
| 47 | + } |
| 48 | + |
| 49 | + // Final check to confirm listeners are cleaned up |
| 50 | + expect(countListeners()).toBe(0); |
| 51 | + }); |
| 52 | +}); |
0 commit comments