Skip to content
Myr

sse.test.tsx

This file

Path

src/helper/streaming/sse.test.tsx

557 lines 路 16.2 KiB 路 TypeScript

Last changed by

chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2

History of this file

Take it

1import { streamSSE } from '.'2/** @jsxImportSource ../../jsx */3import { Context } from '../../context'4import { ErrorBoundary, Suspense } from '../../jsx'56describe('SSE Streaming helper', () => {7  const req = new Request('http://localhost/')8  let c: Context9  beforeEach(() => {10    c = new Context(req)11  })1213  it('Check streamSSE Response', async () => {14    let spy15    const res = streamSSE(c, async (stream) => {16      spy = vi.spyOn(stream, 'close').mockImplementation(async () => {})1718      let id = 019      const maxIterations = 52021      while (id < maxIterations) {22        const message = `Message\nIt is ${id}`23        await stream.writeSSE({ data: message, event: 'time-update', id: String(id++) })24        await stream.sleep(10)25      }26    })2728    expect(res).not.toBeNull()29    expect(res.status).toBe(200)30    expect(res.headers.get('Transfer-Encoding')).toEqual('chunked')31    expect(res.headers.get('Content-Type')).toEqual('text/event-stream')32    expect(res.headers.get('Cache-Control')).toEqual('no-cache')33    expect(res.headers.get('Connection')).toEqual('keep-alive')3435    if (!res.body) {36      throw new Error('Body is null')37    }38    const reader = res.body.getReader()39    const decoder = new TextDecoder()40    for (let i = 0; i < 5; i++) {41      const { value } = await reader.read()42      const decodedValue = decoder.decode(value)4344      // Check the structure and content of the SSE message45      let expectedValue = 'event: time-update\n'46      expectedValue += 'data: Message\n'47      expectedValue += `data: It is ${i}\n`48      expectedValue += `id: ${i}\n\n`49      expect(decodedValue).toBe(expectedValue)50    }51    await new Promise((resolve) => setTimeout(resolve, 100))52    expect(spy).toHaveBeenCalled()53  })5455  it('Check streamSSE Response if aborted by client', async () => {56    let aborted = false57    const res = streamSSE(c, async (stream) => {58      stream.onAbort(() => {59        aborted = true60      })61      for (let i = 0; i < 3; i++) {62        await stream.writeSSE({63          data: `Message ${i}`,64        })65        await stream.sleep(1)66      }67    })68    if (!res.body) {69      throw new Error('Body is null')70    }71    const reader = res.body.getReader()72    const { value } = await reader.read()73    expect(value).toEqual(new TextEncoder().encode('data: Message 0\n\n'))74    reader.cancel()75    expect(aborted).toBeTruthy()76  })7778  it('Check streamSSE Response if aborted by abort signal', async () => {79    // Emulate an old version of Bun (version 1.1.0) for this specific test case80    // @ts-expect-error Bun is not typed81    global.Bun = {82      version: '1.1.0',83    }84    const ac = new AbortController()85    const req = new Request('http://localhost/', { signal: ac.signal })86    const c = new Context(req)8788    let aborted = false89    const res = streamSSE(c, async (stream) => {90      stream.onAbort(() => {91        aborted = true92      })93      for (let i = 0; i < 3; i++) {94        await stream.writeSSE({95          data: `Message ${i}`,96        })97        await stream.sleep(1)98      }99    })100    if (!res.body) {101      throw new Error('Body is null')102    }103    const reader = res.body.getReader()104    const { value } = await reader.read()105    expect(value).toEqual(new TextEncoder().encode('data: Message 0\n\n'))106    ac.abort()107    expect(aborted).toBeTruthy()108  })109110  it('Should include retry in the SSE message', async () => {111    const retryTime = 3000 // 3 seconds112    const res = streamSSE(c, async (stream) => {113      await stream.writeSSE({114        data: 'This is a test message',115        retry: retryTime,116      })117    })118119    expect(res).not.toBeNull()120    expect(res.status).toBe(200)121122    if (!res.body) {123      throw new Error('Body is null')124    }125    const reader = res.body.getReader()126    const decoder = new TextDecoder()127    const { value } = await reader.read()128    const decodedValue = decoder.decode(value)129130    // Check if the retry parameter is included in the SSE message131    const expectedRetryValue = `retry: ${retryTime}\n\n`132    expect(decodedValue).toContain(expectedRetryValue)133  })134135  it('Should accept retry: 0 and not skip it', async () => {136    const res = streamSSE(c, async (stream) => {137      await stream.writeSSE({138        data: 'This is a test message',139        retry: 0,140      })141    })142143    expect(res).not.toBeNull()144    expect(res.status).toBe(200)145146    if (!res.body) {147      throw new Error('Body is null')148    }149    const reader = res.body.getReader()150    const decoder = new TextDecoder()151    const { value } = await reader.read()152    const decodedValue = decoder.decode(value)153154    expect(decodedValue).toContain('retry: 0\n\n')155  })156157  it('Should emit an empty id to reset Last-Event-ID', async () => {158    const res = streamSSE(c, async (stream) => {159      await stream.writeSSE({160        data: 'reset',161        id: '',162      })163    })164165    expect(await res.text()).toBe('data: reset\nid: \n\n')166  })167168  it('Check stream Response if error occurred', async () => {169    const onError = vi.fn()170    const res = streamSSE(171      c,172      async () => {173        throw new Error('Test error')174      },175      onError176    )177    if (!res.body) {178      throw new Error('Body is null')179    }180    const reader = res.body.getReader()181    const decoder = new TextDecoder()182    const { value } = await reader.read()183    const decodedValue = decoder.decode(value)184    expect(decodedValue).toBe('event: error\ndata: Test error\n\n')185    expect(onError).toBeCalledTimes(1)186    expect(onError).toBeCalledWith(new Error('Test error'), expect.anything()) // 2nd argument is StreamingApi instance187  })188189  it('Check streamSSE Response via Promise<string>', async () => {190    const res = streamSSE(c, async (stream) => {191      await stream.writeSSE({ data: Promise.resolve('Async Message') })192    })193194    expect(res).not.toBeNull()195    expect(res.status).toBe(200)196197    if (!res.body) {198      throw new Error('Body is null')199    }200    const reader = res.body.getReader()201    const decoder = new TextDecoder()202    const { value } = await reader.read()203    const decodedValue = decoder.decode(value)204    expect(decodedValue).toBe('data: Async Message\n\n')205  })206207  it('Check streamSSE Response via JSX.Element', async () => {208    const res = streamSSE(c, async (stream) => {209      await stream.writeSSE({ data: <div>Hello</div> })210    })211212    expect(res).not.toBeNull()213    expect(res.status).toBe(200)214215    if (!res.body) {216      throw new Error('Body is null')217    }218    const reader = res.body.getReader()219    const decoder = new TextDecoder()220    const { value } = await reader.read()221    const decodedValue = decoder.decode(value)222    expect(decodedValue).toBe('data: <div>Hello</div>\n\n')223  })224225  it('Check streamSSE Response via ErrorBoundary in success case', async () => {226    const AsyncComponent = async () => Promise.resolve(<div>Async Hello</div>)227    const res = streamSSE(c, async (stream) => {228      await stream.writeSSE({229        data: (230          <ErrorBoundary fallback={<div>Error</div>}>231            <AsyncComponent />232          </ErrorBoundary>233        ),234      })235    })236237    expect(res).not.toBeNull()238    expect(res.status).toBe(200)239240    if (!res.body) {241      throw new Error('Body is null')242    }243    const reader = res.body.getReader()244    const decoder = new TextDecoder()245    const { value } = await reader.read()246    const decodedValue = decoder.decode(value)247    expect(decodedValue).toBe('data: <div>Async Hello</div>\n\n')248  })249250  it('Check streamSSE Response via ErrorBoundary in error case', async () => {251    const AsyncComponent = async () => Promise.reject()252    const res = streamSSE(c, async (stream) => {253      await stream.writeSSE({254        data: (255          <ErrorBoundary fallback={<div>Error</div>}>256            <AsyncComponent />257          </ErrorBoundary>258        ),259      })260    })261262    expect(res).not.toBeNull()263    expect(res.status).toBe(200)264265    if (!res.body) {266      throw new Error('Body is null')267    }268    const reader = res.body.getReader()269    const decoder = new TextDecoder()270    const { value } = await reader.read()271    const decodedValue = decoder.decode(value)272    expect(decodedValue).toBe('data: <div>Error</div>\n\n')273  })274275  it('Check streamSSE Response via Suspense with a multi-line fallback', async () => {276    const AsyncComponent = async () => Promise.resolve(<div>Async Hello</div>)277    const res = streamSSE(c, async (stream) => {278      await stream.writeSSE({279        data: (280          <Suspense fallback={<div>{'Loading...\nPlease wait'}</div>}>281            <AsyncComponent />282          </Suspense>283        ),284      })285    })286287    expect(res).not.toBeNull()288    expect(res.status).toBe(200)289290    if (!res.body) {291      throw new Error('Body is null')292    }293    const reader = res.body.getReader()294    const decoder = new TextDecoder()295    const { value } = await reader.read()296    const decodedValue = decoder.decode(value)297    expect(decodedValue).toBe('data: <div>Async Hello</div>\n\n')298  })299300  it('Check streamSSE Response via ErrorBoundary with multi-line content', async () => {301    const AsyncComponent = async () => Promise.resolve(<div>{'Async\nHello'}</div>)302    const res = streamSSE(c, async (stream) => {303      await stream.writeSSE({304        data: (305          <ErrorBoundary fallback={<div>Error</div>}>306            <Suspense fallback={<div>Loading...</div>}>307              <AsyncComponent />308            </Suspense>309          </ErrorBoundary>310        ),311      })312    })313314    expect(res).not.toBeNull()315    expect(res.status).toBe(200)316317    if (!res.body) {318      throw new Error('Body is null')319    }320    const reader = res.body.getReader()321    const decoder = new TextDecoder()322    const { value } = await reader.read()323    const decodedValue = decoder.decode(value)324    expect(decodedValue).toBe('data: <div>Async\ndata: Hello</div>\n\n')325  })326327  it('Check streamSSE Response via sibling Suspense boundaries with multi-line fallbacks', async () => {328    const One = async () => Promise.resolve(<div>One</div>)329    const Two = async () => Promise.resolve(<div>Two</div>)330    const res = streamSSE(c, async (stream) => {331      await stream.writeSSE({332        data: (333          <div>334            <Suspense fallback={<div>{'Loading1...\nwait'}</div>}>335              <One />336            </Suspense>337            <Suspense fallback={<div>{'Loading2...\nwait'}</div>}>338              <Two />339            </Suspense>340          </div>341        ),342      })343    })344345    expect(res).not.toBeNull()346    expect(res.status).toBe(200)347348    if (!res.body) {349      throw new Error('Body is null')350    }351    const reader = res.body.getReader()352    const decoder = new TextDecoder()353    let decodedValue = ''354    for (;;) {355      const { done, value } = await reader.read()356      if (done) {357        break358      }359      decodedValue += decoder.decode(value)360    }361    expect(decodedValue).toBe('data: <div><div>One</div><div>Two</div></div>\n\n')362  })363364  it('Check streamSSE Response via nested Suspense boundaries with multi-line fallback and content', async () => {365    const Inner = async () => Promise.resolve(<div>{'Inner\nContent'}</div>)366    const Outer = async () =>367      Promise.resolve(368        <Suspense fallback={<div>{'B\nb'}</div>}>369          <Inner />370        </Suspense>371      )372    const res = streamSSE(c, async (stream) => {373      await stream.writeSSE({374        data: (375          <Suspense fallback={<div>{'A\na'}</div>}>376            <Outer />377          </Suspense>378        ),379      })380    })381382    expect(res).not.toBeNull()383    expect(res.status).toBe(200)384385    if (!res.body) {386      throw new Error('Body is null')387    }388    const reader = res.body.getReader()389    const decoder = new TextDecoder()390    let decodedValue = ''391    for (;;) {392      const { done, value } = await reader.read()393      if (done) {394        break395      }396      decodedValue += decoder.decode(value)397    }398    expect(decodedValue).toBe('data: <div>Inner\ndata: Content</div>\n\n')399  })400401  it('Check streamSSE handles \\r (CR) line ending correctly', async () => {402    const res = streamSSE(c, async (stream) => {403      await stream.writeSSE({404        data: 'Line1\rLine2',405        event: 'test-cr',406      })407    })408409    if (!res.body) {410      throw new Error('Body is null')411    }412    const reader = res.body.getReader()413    const decoder = new TextDecoder()414    const { value } = await reader.read()415    const decodedValue = decoder.decode(value)416417    expect(decodedValue).toBe('event: test-cr\ndata: Line1\ndata: Line2\n\n')418  })419420  it('Check streamSSE handles \\r\\n (CRLF) line ending correctly', async () => {421    const res = streamSSE(c, async (stream) => {422      await stream.writeSSE({423        data: 'Line1\r\nLine2',424        event: 'test-crlf',425      })426    })427428    if (!res.body) {429      throw new Error('Body is null')430    }431    const reader = res.body.getReader()432    const decoder = new TextDecoder()433    const { value } = await reader.read()434    const decodedValue = decoder.decode(value)435436    expect(decodedValue).toBe('event: test-crlf\ndata: Line1\ndata: Line2\n\n')437  })438439  it('Check streamSSE handles mixed line endings correctly', async () => {440    const res = streamSSE(c, async (stream) => {441      await stream.writeSSE({442        data: 'A\nB\rC\r\nD',443        event: 'test-mixed',444      })445    })446447    if (!res.body) {448      throw new Error('Body is null')449    }450    const reader = res.body.getReader()451    const decoder = new TextDecoder()452    const { value } = await reader.read()453    const decodedValue = decoder.decode(value)454455    expect(decodedValue).toBe('event: test-mixed\ndata: A\ndata: B\ndata: C\ndata: D\n\n')456  })457458  it('Should throw error if event contains \\n', async () => {459    const onError = vi.fn()460    const res = streamSSE(461      c,462      async (stream) => {463        await stream.writeSSE({ data: 'test', event: 'test\nevent' })464      },465      onError466    )467    if (!res.body) {468      throw new Error('Body is null')469    }470    const reader = res.body.getReader()471    const decoder = new TextDecoder()472    const { value } = await reader.read()473    const decodedValue = decoder.decode(value)474    expect(decodedValue).toContain('event: error')475    expect(onError).toBeCalledTimes(1)476  })477478  it('Should throw error if event contains \\r', async () => {479    const onError = vi.fn()480    const res = streamSSE(481      c,482      async (stream) => {483        await stream.writeSSE({ data: 'test', event: 'test\revent' })484      },485      onError486    )487    if (!res.body) {488      throw new Error('Body is null')489    }490    const reader = res.body.getReader()491    const decoder = new TextDecoder()492    const { value } = await reader.read()493    const decodedValue = decoder.decode(value)494    expect(decodedValue).toContain('event: error')495    expect(onError).toBeCalledTimes(1)496  })497498  it('Should throw error if id contains \\n', async () => {499    const onError = vi.fn()500    const res = streamSSE(501      c,502      async (stream) => {503        await stream.writeSSE({ data: 'test', id: 'test\nid' })504      },505      onError506    )507    if (!res.body) {508      throw new Error('Body is null')509    }510    const reader = res.body.getReader()511    const decoder = new TextDecoder()512    const { value } = await reader.read()513    const decodedValue = decoder.decode(value)514    expect(decodedValue).toContain('event: error')515    expect(onError).toBeCalledTimes(1)516  })517518  it('Should throw error if id contains \\r', async () => {519    const onError = vi.fn()520    const res = streamSSE(521      c,522      async (stream) => {523        await stream.writeSSE({ data: 'test', id: 'test\rid' })524      },525      onError526    )527    if (!res.body) {528      throw new Error('Body is null')529    }530    const reader = res.body.getReader()531    const decoder = new TextDecoder()532    const { value } = await reader.read()533    const decodedValue = decoder.decode(value)534    expect(decodedValue).toContain('event: error')535    expect(onError).toBeCalledTimes(1)536  })537538  it('Check streamSSE handles consecutive \\r correctly', async () => {539    const res = streamSSE(c, async (stream) => {540      await stream.writeSSE({541        data: 'Left\r\rRight',542        event: 'test-double-cr',543      })544    })545546    if (!res.body) {547      throw new Error('Body is null')548    }549    const reader = res.body.getReader()550    const decoder = new TextDecoder()551    const { value } = await reader.read()552    const decodedValue = decoder.decode(value)553554    // Two \r should produce an empty line in between555    expect(decodedValue).toBe('event: test-double-cr\ndata: Left\ndata: \ndata: Right\n\n')556  })557})