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
The walk stopped after 200 commits: lines older than f0b094d point at it.
Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 1–3why, one step back1import { once } from 'node:events'2import type { Server } from 'node:http'3import type { AddressInfo } from 'node:net'chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2
line 4why, one step back4import { createAdaptorServer, serve } from '@hono/node-server'Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 5–279why, one step back5import { Hono } from '../../src'6import { Context } from '../../src/context'7import { env, getRuntimeKey } from '../../src/helper/adapter'8import { stream, streamSSE } from '../../src/helper/streaming'9import { basicAuth } from '../../src/middleware/basic-auth'10import { compress } from '../../src/middleware/compress'11import { jwt } from '../../src/middleware/jwt'1213// Test only minimal patterns.14// See <https://github.com/honojs/node-server> for more tests and information.1516describe('Basic', () => {17 const app = new Hono()1819 app.get('/', (c) => {20 return c.text('Hello! Node.js!')21 })22 app.get('/runtime-name', (c) => {23 return c.text(getRuntimeKey())24 })2526 const agent = createAgent(app)2728 it('Should return 200 response', async () => {29 const res = await agent.get('/')30 expect(res.status).toBe(200)31 await expect(res.text()).resolves.toBe('Hello! Node.js!')32 })3334 it('Should return correct runtime name', async () => {35 const res = await agent.get('/runtime-name')36 expect(res.status).toBe(200)37 await expect(res.text()).resolves.toBe('node')38 })39})4041describe('Environment Variables', () => {42 it('Should return the environment variable', async () => {43 const c = new Context(new Request('http://localhost/'))44 const { NAME } = env<{ NAME: string }>(c)45 expect(NAME).toBe('Node')46 })47})4849describe('Basic Auth Middleware', () => {50 const app = new Hono()5152 const username = 'hono-user-a'53 const password = 'hono-password-a'54 app.use(55 '/auth/*',56 basicAuth({57 username,58 password,59 })60 )6162 app.get('/auth/*', () => new Response('auth'))6364 const agent = createAgent(app)6566 it('Should not authorize, return 401 Response', async () => {67 const res = await agent.get('/auth/a')68 expect(res.status).toBe(401)69 await expect(res.text()).resolves.toBe('Unauthorized')70 })7172 it('Should authorize, return 200 Response', async () => {73 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'74 const res = await agent.get('/auth/a', { headers: { Authorization: `Basic ${credential}` } })75 expect(res.status).toBe(200)76 await expect(res.text()).resolves.toBe('auth')77 })78})7980describe('JWT Auth Middleware', () => {81 const app = new Hono()8283 app.use('/jwt/*', jwt({ secret: 'a-secret', alg: 'HS256' }))84 app.get('/jwt/a', (c) => c.text('auth'))8586 const agent = createAgent(app)8788 it('Should not authorize, return 401 Response', async () => {89 const res = await agent.get('/jwt/a')90 expect(res.status).toBe(401)91 await expect(res.text()).resolves.toBe('Unauthorized')92 })9394 it('Should authorize, return 200 Response', async () => {95 const credential =96 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'97 const res = await agent.get('/jwt/a', { headers: { Authorization: `Bearer ${credential}` } })98 expect(res.status).toBe(200)99 await expect(res.text()).resolves.toBe('auth')100 })101})102103describe('stream', () => {104 const app = new Hono()105106 let aborted = false107108 app.get('/stream', (c) => {109 return stream(c, async (stream) => {110 stream.onAbort(() => {111 aborted = true112 })113 return new Promise<void>((resolve) => {114 stream.onAbort(resolve)115 })116 })117 })118 app.get('/streamHello', (c) => {119 return stream(c, async (stream) => {120 stream.onAbort(() => {121 aborted = true122 })123 await stream.write('Hello')124 })125 })126127 const agent = createAgent(app)128129 beforeEach(() => {130 aborted = false131 })132133 it('Should call onAbort', async () => {134 const controller = new AbortController()135 const req = agent.get('/stream', { signal: controller.signal })136137 expect(aborted).toBe(false)138 await new Promise((resolve) => setTimeout(resolve, 10))139 controller.abort()140 await req.catch(() => {})141 while (!aborted) {142 await new Promise((resolve) => setTimeout(resolve))143 }144 expect(aborted).toBe(true)145 })146147 it('Should not be called onAbort if already closed', async () => {148 expect(aborted).toBe(false)149 const res = await agent.get('/streamHello')150 expect(res.status).toBe(200)151 await expect(res.text()).resolves.toBe('Hello')152 expect(aborted).toBe(false)153 })154})155156describe('streamSSE', () => {157 const app = new Hono()158159 let aborted = false160161 app.get('/stream', (c) => {162 return streamSSE(c, async (stream) => {163 stream.onAbort(() => {164 aborted = true165 })166 return new Promise<void>((resolve) => {167 stream.onAbort(resolve)168 })169 })170 })171 app.get('/streamHello', (c) => {172 return streamSSE(c, async (stream) => {173 stream.onAbort(() => {174 aborted = true175 })176 await stream.write('Hello')177 })178 })179180 const agent = createAgent(app)181182 beforeEach(() => {183 aborted = false184 })185186 it('Should call onAbort', async () => {187 const controller = new AbortController()188 const req = agent.get('/stream', { signal: controller.signal })189190 expect(aborted).toBe(false)191 await new Promise((resolve) => setTimeout(resolve, 10))192 controller.abort()193 await req.catch(() => {})194 while (!aborted) {195 await new Promise((resolve) => setTimeout(resolve))196 }197 expect(aborted).toBe(true)198 })199200 it('Should not be called onAbort if already closed', async () => {201 expect(aborted).toBe(false)202 const res = await agent.get('/streamHello')203 expect(res.status).toBe(200)204 await expect(res.text()).resolves.toBe('Hello')205 expect(aborted).toBe(false)206 })207})208209describe('compress', async () => {210 const cssContent = Array.from({ length: 60 }, () => 'body { color: red; }').join('\n')211 const [externalServer, serverInfo] = await new Promise<[Server, AddressInfo]>((resolve) => {212 const externalApp = new Hono()213 externalApp.get('/style.css', (c) =>214 c.text(cssContent, {215 headers: {216 'Content-Type': 'text/css',217 },218 })219 )220 const server = serve(221 {222 fetch: externalApp.fetch,223 port: 0,224 hostname: '0.0.0.0',225 },226 (serverInfo) => {227 resolve([server as Server, serverInfo])228 }229 )230 })231232 const app = new Hono()233 app.use(compress())234 app.get('/fetch/:file', (c) => {235 return fetch(`http://${serverInfo.address}:${serverInfo.port}/${c.req.param('file')}`)236 })237 const agent = createAgent(app)238239 afterAll(() => {240 externalServer.close()241 })242243 it('Should be compressed a fetch response', async () => {244 const res = await agent.get('/fetch/style.css')245 expect(res.status).toBe(200)246 expect(res.headers.get('content-encoding')).toBe('gzip')247 await expect(res.text()).resolves.toBe(cssContent)248 })249})250251describe('Buffers', () => {252 const app = new Hono()253 .get('/', async (c) => {254 return c.body(Buffer.from('hello'))255 })256 .get('/uint8array', async (c) => {257 return c.body(Uint8Array.from('hello'.split(''), (c) => c.charCodeAt(0)))258 })259260 const agent = createAgent(app)261262 it('should allow returning buffers', async () => {263 const res = await agent.get('/')264 expect(res.status).toBe(200)265 await expect(res.text()).resolves.toBe('hello')266 })267268 it('should allow returning uint8array as well', async () => {269 const res = await agent.get('/uint8array')270 expect(res.status).toBe(200)271 await expect(res.text()).resolves.toBe('hello')272 })273})274275function createAgent(app: Hono) {276 const server = createAdaptorServer(app)277 const listening = once(server.listen(), 'listening')278279 return {chore: remove undici in favor of global fetch (#5168)Nurbekbefore adoptionaed1463
line 280why, one step back280 async get(path: string, init?: RequestInit) {Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 281–282why, one step back281 await listening282 const url = new URL(path, getOrigin())chore: remove undici in favor of global fetch (#5168)Nurbekbefore adoptionaed1463
line 283why, one step back283 return fetch(url, init)Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 284–296why, one step back284 },285 }286287 function getOrigin(): string {288 let address = server.address()289290 if (typeof address === 'object') {291 address = address?.port ? `http://localhost:${address.port}` : 'http://localhost'292 }293294 return address295 }296}