Skip to content
Myr

index.test.tsx

This file

Path

runtime-tests/bun/index.test.tsx

268 lines · 7.7 KiB · TypeScript

Last changed by

test: move adapter runtime tests into `adapters/*` (#5466)Yusuke Wadabefore adoption645ddd6

History of this file

Take it

The walk stopped after 200 commits: lines older than f0b094d point at it.

test: move adapter runtime tests into `adapters/*` (#5466)Yusuke Wadabefore adoption645ddd6

line 1why, one step back
1import { afterEach, beforeEach, describe, expect, it } from 'vitest'

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 2–268why, one step back
2import { stream, streamSSE } from '../..//src/helper/streaming'
3import { Context } from '../../src/context'4import { env, getRuntimeKey } from '../../src/helper/adapter'5import { Hono } from '../../src/index'6import type { PropsWithChildren } from '../../src/jsx'7import { basicAuth } from '../../src/middleware/basic-auth'8import { jwt } from '../../src/middleware/jwt'910declare module '../../src/index' {11 interface ContextRenderer {12 (content: string | Promise<string>, head: { title: string }): Response | Promise<Response>13 }14}1516// Test just only minimal patterns.17// Because others are tested well in Cloudflare Workers environment already.1819Bun.env.NAME = 'Bun'2021describe('Basic', () => {22 const app = new Hono()23 app.get('/a/:foo', (c) => {24 c.header('x-param', c.req.param('foo'))25 c.header('x-query', c.req.query('q'))26 return c.text('Hello Bun!')27 })2829 it('Should return 200 Response', async () => {30 const req = new Request('http://localhost/a/foo?q=bar')31 const res = await app.request(req)32 expect(res.status).toBe(200)33 expect(await res.text()).toBe('Hello Bun!')34 expect(res.headers.get('x-param')).toBe('foo')35 expect(res.headers.get('x-query')).toBe('bar')36 })3738 it('returns current runtime (bun)', async () => {39 expect(getRuntimeKey()).toBe('bun')40 })41})4243describe('Environment Variables', () => {44 it('Should return the environment variable', async () => {45 const c = new Context(new Request('http://localhost/'))46 const { NAME } = env<{ NAME: string }>(c)47 expect(NAME).toBe('Bun')48 })49})5051describe('Basic Auth Middleware', () => {52 const app = new Hono()5354 const username = 'hono-user-a'55 const password = 'hono-password-a'56 app.use(57 '/auth/*',58 basicAuth({59 username,60 password,61 })62 )6364 app.get('/auth/*', () => new Response('auth'))6566 it('Should not authorize, return 401 Response', async () => {67 const req = new Request('http://localhost/auth/a')68 const res = await app.request(req)69 expect(res.status).toBe(401)70 expect(await res.text()).toBe('Unauthorized')71 })7273 it('Should authorize, return 200 Response', async () => {74 const credential = 'aG9uby11c2VyLWE6aG9uby1wYXNzd29yZC1h'75 const req = new Request('http://localhost/auth/a')76 req.headers.set('Authorization', `Basic ${credential}`)77 const res = await app.request(req)78 expect(res.status).toBe(200)79 expect(await res.text()).toBe('auth')80 })81})8283// Bun support WebCrypto since v0.2.284// So, JWT middleware works well.85describe('JWT Auth Middleware', () => {86 const app = new Hono()87 app.use('/jwt/*', jwt({ secret: 'a-secret', alg: 'HS256' }))88 app.get('/jwt/a', (c) => c.text('auth'))8990 it('Should not authorize, return 401 Response', async () => {91 const req = new Request('http://localhost/jwt/a')92 const res = await app.request(req)93 expect(res.status).toBe(401)94 expect(await res.text()).toBe('Unauthorized')95 })9697 it('Should authorize, return 200 Response', async () => {98 const credential =99 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJtZXNzYWdlIjoiaGVsbG8gd29ybGQifQ.B54pAqIiLbu170tGQ1rY06Twv__0qSHTA0ioQPIOvFE'100 const req = new Request('http://localhost/jwt/a')101 req.headers.set('Authorization', `Bearer ${credential}`)102 const res = await app.request(req)103 expect(res.status).toBe(200)104 expect(await res.text()).toBe('auth')105 })106})107108// To enable JSX middleware,109// set "jsxImportSource": "hono/jsx" in the tsconfig.json110describe('JSX Middleware', () => {111 const app = new Hono()112113 const Layout = (props: PropsWithChildren) => {114 return <html>{props.children}</html>115 }116117 app.get('/', (c) => {118 return c.html(<h1>Hello</h1>)119 })120 app.get('/nest', (c) => {121 return c.html(122 <h1>123 <a href='/top'>Hello</a>124 </h1>125 )126 })127 app.get('/layout', (c) => {128 return c.html(129 <Layout>130 <p>hello</p>131 </Layout>132 )133 })134135 it('Should return rendered HTML', async () => {136 const res = await app.request(new Request('http://localhost/'))137 expect(res.status).toBe(200)138 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')139 expect(await res.text()).toBe('<h1>Hello</h1>')140 })141142 it('Should return rendered HTML with nest', async () => {143 const res = await app.request(new Request('http://localhost/nest'))144 expect(res.status).toBe(200)145 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')146 expect(await res.text()).toBe('<h1><a href="/top">Hello</a></h1>')147 })148149 it('Should return rendered HTML with Layout', async () => {150 const res = await app.request(new Request('http://localhost/layout'))151 expect(res.status).toBe(200)152 expect(res.headers.get('Content-Type')).toBe('text/html; charset=UTF-8')153 expect(await res.text()).toBe('<html><p>hello</p></html>')154 })155})156157describe('streaming', () => {158 const app = new Hono()159 let server: ReturnType<typeof Bun.serve>160 let aborted = false161162 app.get('/stream', (c) => {163 return stream(c, async (stream) => {164 stream.onAbort(() => {165 aborted = true166 })167 return new Promise<void>((resolve) => {168 stream.onAbort(resolve)169 })170 })171 })172 app.get('/streamHello', (c) => {173 return stream(c, async (stream) => {174 stream.onAbort(() => {175 aborted = true176 })177 await stream.write('Hello')178 })179 })180 app.get('/streamSSE', (c) => {181 return streamSSE(c, async (stream) => {182 stream.onAbort(() => {183 aborted = true184 })185 return new Promise<void>((resolve) => {186 stream.onAbort(resolve)187 })188 })189 })190 app.get('/streamSSEHello', (c) => {191 return streamSSE(c, async (stream) => {192 stream.onAbort(() => {193 aborted = true194 })195 await stream.write('Hello')196 })197 })198199 beforeEach(() => {200 aborted = false201 server = Bun.serve({ port: 0, fetch: app.fetch })202 })203204 afterEach(() => {205 server.stop()206 })207208 describe('stream', () => {209 it('Should call onAbort', async () => {210 const ac = new AbortController()211 const req = new Request(`http://localhost:${server.port}/stream`, {212 signal: ac.signal,213 })214 expect(aborted).toBe(false)215 const res = fetch(req).catch(() => {})216 await new Promise((resolve) => setTimeout(resolve, 10))217 ac.abort()218 await res219 while (!aborted) {220 await new Promise((resolve) => setTimeout(resolve))221 }222 expect(aborted).toBe(true)223 })224225 it('Should not be called onAbort if already closed', async () => {226 expect(aborted).toBe(false)227 const res = await fetch(`http://localhost:${server.port}/streamHello`)228 expect(await res.text()).toBe('Hello')229 expect(aborted).toBe(false)230 })231 })232233 describe('streamSSE', () => {234 it('Should call onAbort', async () => {235 const ac = new AbortController()236 const req = new Request(`http://localhost:${server.port}/streamSSE`, {237 signal: ac.signal,238 })239 const res = fetch(req).catch(() => {})240 await new Promise((resolve) => setTimeout(resolve, 10))241 ac.abort()242 await res243 while (!aborted) {244 await new Promise((resolve) => setTimeout(resolve))245 }246 expect(aborted).toBe(true)247 })248249 it('Should not be called onAbort if already closed', async () => {250 expect(aborted).toBe(false)251 const res = await fetch(`http://localhost:${server.port}/streamSSEHello`)252 expect(await res.text()).toBe('Hello')253 expect(aborted).toBe(false)254 })255 })256})257258describe('Buffers', () => {259 const app = new Hono().get('/', async (c) => {260 return c.body(Buffer.from('hello'))261 })262263 it('should allow returning buffers', async () => {264 const res = await app.request(new Request('http://localhost/'))265 expect(res.status).toBe(200)266 expect(await res.text()).toBe('hello')267 })268})