|
| 1 | +import { convertAsyncIteratorToReadableStream } from './convert-async-iterator-to-readable-stream'; |
| 2 | +import { describe, it, expect } from 'vitest'; |
| 3 | + |
| 4 | +async function* makeGenerator(onFinally: () => void) { |
| 5 | + try { |
| 6 | + let i = 0; |
| 7 | + while (true) { |
| 8 | + await new Promise(r => setTimeout(r, 0)); |
| 9 | + yield i++; |
| 10 | + } |
| 11 | + } finally { |
| 12 | + onFinally(); |
| 13 | + } |
| 14 | +} |
| 15 | + |
| 16 | +describe('convertAsyncIteratorToReadableStream', () => { |
| 17 | + it('calls iterator.return() on cancel and triggers finally', async () => { |
| 18 | + let finallyCalled = false; |
| 19 | + const it = makeGenerator(() => { |
| 20 | + finallyCalled = true; |
| 21 | + }); |
| 22 | + const stream = convertAsyncIteratorToReadableStream(it); |
| 23 | + const reader = stream.getReader(); |
| 24 | + |
| 25 | + await reader.read(); |
| 26 | + |
| 27 | + await reader.cancel('stop'); |
| 28 | + |
| 29 | + // give microtasks a tick for finally to run |
| 30 | + await new Promise(r => setTimeout(r, 0)); |
| 31 | + |
| 32 | + expect(finallyCalled).toBe(true); |
| 33 | + }); |
| 34 | + |
| 35 | + it('does not enqueue further values after cancel', async () => { |
| 36 | + const it = makeGenerator(() => {}); |
| 37 | + const stream = convertAsyncIteratorToReadableStream(it); |
| 38 | + const reader = stream.getReader(); |
| 39 | + |
| 40 | + await reader.read(); |
| 41 | + await reader.cancel('stop'); |
| 42 | + |
| 43 | + const { done, value } = await reader.read(); |
| 44 | + expect(done).toBe(true); |
| 45 | + expect(value).toBeUndefined(); |
| 46 | + }); |
| 47 | + |
| 48 | + it('works with iterator without return() method', async () => { |
| 49 | + const it: AsyncIterator<number> = { |
| 50 | + async next() { |
| 51 | + return { value: 42, done: false }; |
| 52 | + }, |
| 53 | + }; |
| 54 | + const stream = convertAsyncIteratorToReadableStream(it); |
| 55 | + const reader = stream.getReader(); |
| 56 | + |
| 57 | + const { value } = await reader.read(); |
| 58 | + expect(value).toBe(42); |
| 59 | + |
| 60 | + await expect(reader.cancel()).resolves.toBeUndefined(); |
| 61 | + }); |
| 62 | + |
| 63 | + it('ignores errors from iterator.return()', async () => { |
| 64 | + const it: AsyncIterator<number> = { |
| 65 | + async next() { |
| 66 | + return { value: 1, done: false }; |
| 67 | + }, |
| 68 | + async return() { |
| 69 | + throw new Error('return() failed'); |
| 70 | + }, |
| 71 | + }; |
| 72 | + const stream = convertAsyncIteratorToReadableStream(it); |
| 73 | + const reader = stream.getReader(); |
| 74 | + |
| 75 | + await reader.read(); |
| 76 | + await expect(reader.cancel()).resolves.toBeUndefined(); |
| 77 | + }); |
| 78 | +}); |
0 commit comments