|
| 1 | +import { expect, test } from "@playwright/test"; |
| 2 | + |
| 3 | +test("streaming should work in route handler", async ({ page }) => { |
| 4 | + const ITERATOR_LENGTH = 10; |
| 5 | + |
| 6 | + const res = await page.goto("/streaming", { |
| 7 | + // we set waitUntil: "commit" to ensure that the response is streamed |
| 8 | + // without this option, the response would be buffered and sent all at once |
| 9 | + // we could also drop the `await` aswell, but then we can't see the headers first. |
| 10 | + waitUntil: "commit", |
| 11 | + }); |
| 12 | + |
| 13 | + expect(res?.headers()["content-type"]).toBe("text/html; charset=utf-8"); |
| 14 | + expect(res?.headers()["cache-control"]).toBe("no-cache, no-transform"); |
| 15 | + // AWS API Gateway remaps the connection header to `x-amzn-remapped-connection` |
| 16 | + expect(res?.headers()["x-amzn-remapped-connection"]).toBe("keep-alive"); |
| 17 | + |
| 18 | + // wait for first number to be present |
| 19 | + await page.getByTestId("iteratorCount").first().waitFor(); |
| 20 | + |
| 21 | + const seenNumbers: Array<{ number: string; time: number }> = []; |
| 22 | + const startTime = Date.now(); |
| 23 | + |
| 24 | + const initialParagraphs = await page.getByTestId("iteratorCount").count(); |
| 25 | + // fail if all paragraphs appear at once |
| 26 | + // this is a safeguard to ensure that the response is streamed and not buffered all at once |
| 27 | + expect(initialParagraphs).toBe(1); |
| 28 | + |
| 29 | + while ( |
| 30 | + seenNumbers.length < ITERATOR_LENGTH && |
| 31 | + Date.now() - startTime < 11000 |
| 32 | + ) { |
| 33 | + const elements = await page.getByTestId("iteratorCount").all(); |
| 34 | + if (elements.length > seenNumbers.length) { |
| 35 | + expect(elements.length).toBe(seenNumbers.length + 1); |
| 36 | + const newElement = elements[elements.length - 1]; |
| 37 | + const timestamp = await newElement.getAttribute("data-timestamp"); |
| 38 | + seenNumbers.push({ |
| 39 | + number: await newElement.innerText(), |
| 40 | + time: Number.parseInt(timestamp || "0", 10), |
| 41 | + }); |
| 42 | + } |
| 43 | + await page.waitForTimeout(100); |
| 44 | + } |
| 45 | + |
| 46 | + expect(seenNumbers.map((n) => n.number)).toEqual( |
| 47 | + [...Array(ITERATOR_LENGTH)].map((_, i) => String(i + 1)), |
| 48 | + ); |
| 49 | + |
| 50 | + // verify streaming timing using server timestamps |
| 51 | + for (let i = 1; i < seenNumbers.length; i++) { |
| 52 | + const timeDiff = seenNumbers[i].time - seenNumbers[i - 1].time; |
| 53 | + expect(timeDiff).toBeGreaterThanOrEqual(900); |
| 54 | + } |
| 55 | +}); |
0 commit comments