index.test.ts
This file
Path
runtime-tests/node/index.test.ts
296 lines 路 7.9 KiB 路 TypeScript
Last changed by
chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
History of this fileTake it
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297import { once } from 'node:events'import type { Server } from 'node:http'import type { AddressInfo } from 'node:net'import { createAdaptorServer, serve } from '@hono/node-server'import { Hono } from '../../src'import { Context } from '../../src/context'import { env, getRuntimeKey } from '../../src/helper/adapter'import { stream, streamSSE } from '../../src/helper/streaming'import { basicAuth } from '../../src/middleware/basic-auth'import { compress } from '../../src/middleware/compress'import { jwt } from '../../src/middleware/jwt'
// Test only minimal patterns.// See <https://github.com/honojs/node-server> for more tests and information.
describe('Basic', () => { const app = new Hono()
app.get('/', (c) => { return c.text('Hello! Node.js!') }) app.get('/runtime-name', (c) => { return c.text(getRuntimeKey()) })
const agent = createAgent(app)
it('Should return 200 response', async () => { const res = await agent.get('/') expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('Hello! Node.js!') })
it('Should return correct runtime name', async () => { const res = await agent.get('/runtime-name') expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('node') })})
describe('Environment Variables', () => { it('Should return the environment variable', async () => { const c = new Context(new Request('http://localhost/')) const { NAME } = env<{ NAME: string }>(c) expect(NAME).toBe('Node') })})
describe('Basic Auth Middleware', () => { const app = new Hono()
const username = 'hono-user-a' const password = 'hono-password-a' app.use( '/auth/*', basicAuth({ username, password, }) )
app.get('/auth/*', () => new Response('auth'))
const agent = createAgent(app)
it('Should not authorize, return 401 Response', async () => { const res = await agent.get('/auth/a') expect(res.status).toBe(401) await expect(res.text()).resolves.toBe('Unauthorized') })
it('Should authorize, return 200 Response', async () => { const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h' const res = await agent.get('/auth/a', { headers: { Authorization: `Basic ${credential}` } }) expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('auth') })})
describe('JWT Auth Middleware', () => { const app = new Hono()
app.use('/jwt/*', jwt({ secret: 'a-secret', alg: 'HS256' })) app.get('/jwt/a', (c) => c.text('auth'))
const agent = createAgent(app)
it('Should not authorize, return 401 Response', async () => { const res = await agent.get('/jwt/a') expect(res.status).toBe(401) await expect(res.text()).resolves.toBe('Unauthorized') })
it('Should authorize, return 200 Response', async () => { const credential = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE' const res = await agent.get('/jwt/a', { headers: { Authorization: `Bearer ${credential}` } }) expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('auth') })})
describe('stream', () => { const app = new Hono()
let aborted = false
app.get('/stream', (c) => { return stream(c, async (stream) => { stream.onAbort(() => { aborted = true }) return new Promise<void>((resolve) => { stream.onAbort(resolve) }) }) }) app.get('/streamHello', (c) => { return stream(c, async (stream) => { stream.onAbort(() => { aborted = true }) await stream.write('Hello') }) })
const agent = createAgent(app)
beforeEach(() => { aborted = false })
it('Should call onAbort', async () => { const controller = new AbortController() const req = agent.get('/stream', { signal: controller.signal })
expect(aborted).toBe(false) await new Promise((resolve) => setTimeout(resolve, 10)) controller.abort() await req.catch(() => {}) while (!aborted) { await new Promise((resolve) => setTimeout(resolve)) } expect(aborted).toBe(true) })
it('Should not be called onAbort if already closed', async () => { expect(aborted).toBe(false) const res = await agent.get('/streamHello') expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('Hello') expect(aborted).toBe(false) })})
describe('streamSSE', () => { const app = new Hono()
let aborted = false
app.get('/stream', (c) => { return streamSSE(c, async (stream) => { stream.onAbort(() => { aborted = true }) return new Promise<void>((resolve) => { stream.onAbort(resolve) }) }) }) app.get('/streamHello', (c) => { return streamSSE(c, async (stream) => { stream.onAbort(() => { aborted = true }) await stream.write('Hello') }) })
const agent = createAgent(app)
beforeEach(() => { aborted = false })
it('Should call onAbort', async () => { const controller = new AbortController() const req = agent.get('/stream', { signal: controller.signal })
expect(aborted).toBe(false) await new Promise((resolve) => setTimeout(resolve, 10)) controller.abort() await req.catch(() => {}) while (!aborted) { await new Promise((resolve) => setTimeout(resolve)) } expect(aborted).toBe(true) })
it('Should not be called onAbort if already closed', async () => { expect(aborted).toBe(false) const res = await agent.get('/streamHello') expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('Hello') expect(aborted).toBe(false) })})
describe('compress', async () => { const cssContent = Array.from({ length: 60 }, () => 'body { color: red; }').join('\n') const [externalServer, serverInfo] = await new Promise<[Server, AddressInfo]>((resolve) => { const externalApp = new Hono() externalApp.get('/style.css', (c) => c.text(cssContent, { headers: { 'Content-Type': 'text/css', }, }) ) const server = serve( { fetch: externalApp.fetch, port: 0, hostname: '0.0.0.0', }, (serverInfo) => { resolve([server as Server, serverInfo]) } ) })
const app = new Hono() app.use(compress()) app.get('/fetch/:file', (c) => { return fetch(`http://${serverInfo.address}:${serverInfo.port}/${c.req.param('file')}`) }) const agent = createAgent(app)
afterAll(() => { externalServer.close() })
it('Should be compressed a fetch response', async () => { const res = await agent.get('/fetch/style.css') expect(res.status).toBe(200) expect(res.headers.get('content-encoding')).toBe('gzip') await expect(res.text()).resolves.toBe(cssContent) })})
describe('Buffers', () => { const app = new Hono() .get('/', async (c) => { return c.body(Buffer.from('hello')) }) .get('/uint8array', async (c) => { return c.body(Uint8Array.from('hello'.split(''), (c) => c.charCodeAt(0))) })
const agent = createAgent(app)
it('should allow returning buffers', async () => { const res = await agent.get('/') expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('hello') })
it('should allow returning uint8array as well', async () => { const res = await agent.get('/uint8array') expect(res.status).toBe(200) await expect(res.text()).resolves.toBe('hello') })})
function createAgent(app: Hono) { const server = createAdaptorServer(app) const listening = once(server.listen(), 'listening')
return { async get(path: string, init?: RequestInit) { await listening const url = new URL(path, getOrigin()) return fetch(url, init) }, }
function getOrigin(): string { let address = server.address()
if (typeof address === 'object') { address = address?.port ? `http://localhost:${address.port}` : 'http://localhost' }
return address }}