2023-03-06 13:12:22 +01:00
|
|
|
import { unstable_dev } from 'wrangler'
|
|
|
|
import type { UnstableDevWorker } from 'wrangler'
|
2024-06-02 17:14:11 +02:00
|
|
|
import { WebSocket } from 'ws'
|
2023-03-06 13:12:22 +01:00
|
|
|
|
2024-06-02 15:49:40 +02:00
|
|
|
describe('workerd', () => {
|
2023-03-06 13:12:22 +01:00
|
|
|
let worker: UnstableDevWorker
|
|
|
|
|
|
|
|
beforeAll(async () => {
|
2024-09-17 07:51:43 +02:00
|
|
|
worker = await unstable_dev('./runtime-tests/workerd/index.ts', {
|
2023-03-06 13:12:22 +01:00
|
|
|
vars: {
|
2024-06-02 15:49:40 +02:00
|
|
|
NAME: 'Hono',
|
2023-03-06 13:12:22 +01:00
|
|
|
},
|
|
|
|
experimental: { disableExperimentalWarning: true },
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
afterAll(async () => {
|
|
|
|
await worker.stop()
|
|
|
|
})
|
|
|
|
|
2024-06-02 15:49:40 +02:00
|
|
|
it('Should return 200 response with the runtime key', async () => {
|
2023-03-06 13:12:22 +01:00
|
|
|
const res = await worker.fetch('/')
|
|
|
|
expect(res.status).toBe(200)
|
2024-06-02 15:49:40 +02:00
|
|
|
expect(await res.text()).toBe('Hello from workerd')
|
2023-03-06 13:12:22 +01:00
|
|
|
})
|
|
|
|
|
2024-06-02 15:49:40 +02:00
|
|
|
it('Should return 200 response with the environment variable', async () => {
|
2023-03-06 13:12:22 +01:00
|
|
|
const res = await worker.fetch('/env')
|
|
|
|
expect(res.status).toBe(200)
|
2024-06-02 15:49:40 +02:00
|
|
|
expect(await res.text()).toBe('Hono')
|
2023-03-06 13:12:22 +01:00
|
|
|
})
|
|
|
|
})
|
2024-06-02 17:14:11 +02:00
|
|
|
|
|
|
|
describe('workerd with WebSocket', () => {
|
|
|
|
// worker.fetch does not support WebSocket:
|
|
|
|
// https://github.com/cloudflare/workers-sdk/issues/4573#issuecomment-1850420973
|
|
|
|
it('Should handle the WebSocket connection correctly', async () => {
|
2024-09-17 07:51:43 +02:00
|
|
|
const worker = await unstable_dev('./runtime-tests/workerd/index.ts', {
|
2024-06-02 17:14:11 +02:00
|
|
|
experimental: { disableExperimentalWarning: true },
|
|
|
|
})
|
|
|
|
const ws = new WebSocket(`ws://${worker.address}:${worker.port}/ws`)
|
|
|
|
|
|
|
|
const openHandler = vi.fn()
|
|
|
|
const messageHandler = vi.fn()
|
|
|
|
const closeHandler = vi.fn()
|
|
|
|
|
|
|
|
const waitForOpen = new Promise((resolve) => {
|
|
|
|
ws.addEventListener('open', () => {
|
|
|
|
openHandler()
|
|
|
|
ws.send('Hello')
|
|
|
|
resolve(undefined)
|
|
|
|
})
|
|
|
|
ws.addEventListener('close', async () => {
|
|
|
|
closeHandler()
|
|
|
|
})
|
|
|
|
ws.addEventListener('message', async (event) => {
|
|
|
|
messageHandler(event.data)
|
|
|
|
ws.close()
|
|
|
|
})
|
|
|
|
})
|
|
|
|
|
|
|
|
await waitForOpen
|
|
|
|
await worker.stop()
|
|
|
|
|
|
|
|
expect(openHandler).toHaveBeenCalled()
|
|
|
|
expect(messageHandler).toHaveBeenCalledWith('Hello')
|
|
|
|
expect(closeHandler).toHaveBeenCalled()
|
|
|
|
})
|
|
|
|
})
|