Skip to content

Commit

Permalink
test: add runtime request handler test
Browse files Browse the repository at this point in the history
  • Loading branch information
kettanaito committed Oct 4, 2024
1 parent b11ba9b commit 852870a
Show file tree
Hide file tree
Showing 2 changed files with 59 additions and 3 deletions.
4 changes: 1 addition & 3 deletions test/browser/sse-api/sse.server.connect.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -91,7 +91,7 @@ test('forwards message event from the server to the client automatically', async
const { setupWorker, sse } = window.msw

const worker = setupWorker(
sse(url, ({ client, server }) => {
sse(url, ({ server }) => {
server.connect()
}),
)
Expand All @@ -102,8 +102,6 @@ test('forwards message event from the server to the client automatically', async
return new Promise<void>((resolve, reject) => {
const source = new EventSource(url)
source.addEventListener('message', (event) => {
console.log('client got:', event.type, event.data)

resolve(JSON.parse(event.data))
})
source.onerror = () => reject(new Error('EventSource connection failed'))
Expand Down
58 changes: 58 additions & 0 deletions test/browser/sse-api/sse.use.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,58 @@
import { setupWorker, sse } from 'msw/browser'
import { test, expect } from '../playwright.extend'

declare namespace window {
export const msw: {
setupWorker: typeof setupWorker
sse: typeof sse
}
}

test('supports server-sent event handler overrides', async ({
loadExample,
page,
}) => {
await loadExample(require.resolve('./sse.mocks.ts'), {
skipActivation: true,
})

const workerRef = await page.evaluateHandle(async () => {
const { setupWorker, sse } = window.msw

const worker = setupWorker(
sse('http://localhost/stream', ({ client }) => {
client.send({ data: 'happy-path' })
}),
)
await worker.start()
return worker
})

await page.evaluate((worker) => {
const { sse } = window.msw

worker.use(
// Adding this runtime request handler will make it
// take precedence over the happy path handler above.
sse('http://localhost/stream', ({ client }) => {
// Queue the data for the next tick to rule out
// the happy path handler from executing.
queueMicrotask(() => {
client.send({ data: 'override' })
})
}),
)
}, workerRef)

const message = await page.evaluate(() => {
return new Promise((resolve, reject) => {
const source = new EventSource('http://localhost/stream')
source.addEventListener('message', (event) => {
resolve(event.data)
})
source.onerror = reject
})
})

expect(message).toBe('override')
})

0 comments on commit 852870a

Please sign in to comment.