Skip to content

Commit

Permalink
test(browser): add ReadableStream response body test (#1770)
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito authored Oct 15, 2023
1 parent 595d6f3 commit b028c66
Show file tree
Hide file tree
Showing 2 changed files with 75 additions and 0 deletions.
29 changes: 29 additions & 0 deletions test/browser/rest-api/response/body/body-stream.mocks.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
import { http, HttpResponse, delay } from 'msw'
import { setupWorker } from 'msw/browser'

const encoder = new TextEncoder()
const chunks = ['hello', 'streaming', 'world']

const worker = setupWorker(
http.get('/stream', () => {
const stream = new ReadableStream({
async start(controller) {
for (const chunk of chunks) {
controller.enqueue(encoder.encode(chunk))
await delay(250)
}

controller.close()
},
})

return new HttpResponse(stream, {
headers: {
'Content-Type': 'application/octet-stream',
'Content-Length': chunks.join('').length.toString(),
},
})
}),
)

worker.start()
46 changes: 46 additions & 0 deletions test/browser/rest-api/response/body/body-stream.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,46 @@
import { test, expect } from '../../../playwright.extend'

test('responds with a mocked ReadableStream response', async ({
loadExample,
page,
}) => {
await loadExample(require.resolve('./body-stream.mocks.ts'))

const chunks = await page.evaluate(() => {
return fetch('/stream').then(async (res) => {
if (res.body === null) {
return []
}

const decoder = new TextDecoder()
const chunks: Array<{ text: string; timestamp: number }> = []
const reader = res.body.getReader()

while (true) {
const { value, done } = await reader.read()

if (done) {
return chunks
}

chunks.push({
text: decoder.decode(value),
timestamp: Date.now(),
})
}
})
})

// Must stream the mocked response in three chunks.
const chunksText = chunks.map((chunk) => chunk.text)
expect(chunksText).toEqual(['hello', 'streaming', 'world'])

const chunkDeltas = chunks.map((chunk, index) => {
const prevChunk = chunks[index - 1]
return prevChunk ? chunk.timestamp - prevChunk.timestamp : 0
})

expect(chunkDeltas[0]).toBe(0)
expect(chunkDeltas[1]).toBeGreaterThanOrEqual(200)
expect(chunkDeltas[2]).toBeGreaterThanOrEqual(200)
})

0 comments on commit b028c66

Please sign in to comment.