hono.test.ts
This file
Path
src/hono.test.ts
3,814 lines · 108.6 KiB · TypeScript
Last changed by
fix(trie-router): match suffix wildcard routes (#5236)Taku Amanobefore adoption63bbcf5
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–475why, one step back1/* eslint-disable @typescript-eslint/no-unused-vars */2/* eslint-disable @typescript-eslint/ban-ts-comment */3import { expectTypeOf } from 'vitest'4import { hc } from './client'5import type { Context, ExecutionContext } from './context'6import { Hono } from './hono'7import { HTTPException } from './http-exception'8import { logger } from './middleware/logger'9import { poweredBy } from './middleware/powered-by'10import { RegExpRouter } from './router/reg-exp-router'11import { SmartRouter } from './router/smart-router'12import { TrieRouter } from './router/trie-router'13import type { Handler, MiddlewareHandler, Next } from './types'14import type { Equal, Expect } from './utils/types'15import { getPath } from './utils/url'1617// https://stackoverflow.com/a/6566640218function throwExpression(errorMessage: string): never {19 throw new Error(errorMessage)20}2122type Env = {23 Bindings: {24 _: string25 }26}2728const createResponseProxy = (response: Response) => {29 return new Proxy(response, {30 get(target, prop, receiver) {31 const value = target[prop as keyof Response]32 if (typeof value === 'function') {33 return Object.defineProperties(34 function (...args: unknown[]) {35 // @ts-expect-error: `this` context is intentionally dynamic for proxy method binding36 return Reflect.apply(value, this === receiver ? target : this, args)37 },38 {39 name: { value: value.name },40 length: { value: value.length },41 }42 )43 }44 return value45 },46 })47}4849describe('GET Request', () => {50 describe('without middleware', () => {51 // In other words, this is a test for cases that do not use `compose()`5253 const app = new Hono<Env>()5455 app.get('/hello', async () => {56 return new Response('hello', {57 status: 200,58 statusText: 'Hono is OK',59 })60 })6162 app.get('/hello-with-shortcuts', (c) => {63 c.header('X-Custom', 'This is Hono')64 c.status(201)65 return c.html('<h1>Hono!!!</h1>')66 })6768 app.get('/hello-env', (c) => {69 return c.json(c.env)70 })7172 app.get('/proxy-object', () => createResponseProxy(new Response('proxy')))7374 app.get('/async-proxy-object', async () => createResponseProxy(new Response('proxy')))7576 it('GET http://localhost/hello is ok', async () => {77 const res = await app.request('http://localhost/hello')78 expect(res).not.toBeNull()79 expect(res.status).toBe(200)80 expect(res.statusText).toBe('Hono is OK')81 expect(await res.text()).toBe('hello')82 })8384 it('GET httphello is ng', async () => {85 const res = await app.request('httphello')86 expect(res.status).toBe(404)87 })8889 it('GET /hello is ok', async () => {90 const res = await app.request('/hello')91 expect(res).not.toBeNull()92 expect(res.status).toBe(200)93 expect(res.statusText).toBe('Hono is OK')94 expect(await res.text()).toBe('hello')95 })9697 it('GET hello is ok', async () => {98 const res = await app.request('hello')99 expect(res).not.toBeNull()100 expect(res.status).toBe(200)101 expect(res.statusText).toBe('Hono is OK')102 expect(await res.text()).toBe('hello')103 })104105 it('GET /hello-with-shortcuts is ok', async () => {106 const res = await app.request('http://localhost/hello-with-shortcuts')107 expect(res).not.toBeNull()108 expect(res.status).toBe(201)109 expect(res.headers.get('X-Custom')).toBe('This is Hono')110 expect(res.headers.get('Content-Type')).toMatch(/text\/html/)111 expect(await res.text()).toBe('<h1>Hono!!!</h1>')112 })113114 it('GET / is not found', async () => {115 const res = await app.request('http://localhost/')116 expect(res).not.toBeNull()117 expect(res.status).toBe(404)118 })119120 it('GET /hello-env is ok', async () => {121 const res = await app.request('/hello-env', undefined, { HELLO: 'world' })122 expect(res.status).toBe(200)123 expect(await res.json()).toEqual({ HELLO: 'world' })124 })125126 it('GET /proxy-object is ok', async () => {127 const res = await app.request('/proxy-object')128 expect(res).not.toBeNull()129 expect(res.status).toBe(200)130 expect(await res.text()).toBe('proxy')131 })132133 it('GET /async-proxy-object is ok', async () => {134 const res = await app.request('/proxy-object')135 expect(res).not.toBeNull()136 expect(res.status).toBe(200)137 expect(await res.text()).toBe('proxy')138 })139 })140141 describe('with middleware', () => {142 // when using `compose()`143144 const app = new Hono<Env>()145146 app.use('*', async (ctx, next) => {147 await next()148 })149150 app.get('/hello', async () => {151 return new Response('hello', {152 status: 200,153 statusText: 'Hono is OK',154 })155 })156157 app.get('/hello-with-shortcuts', (c) => {158 c.header('X-Custom', 'This is Hono')159 c.status(201)160 return c.html('<h1>Hono!!!</h1>')161 })162163 app.get('/hello-env', (c) => {164 return c.json(c.env)165 })166167 app.get('/proxy-object', () => createResponseProxy(new Response('proxy')))168169 app.get('/async-proxy-object', async () => createResponseProxy(new Response('proxy')))170171 it('GET http://localhost/hello is ok', async () => {172 const res = await app.request('http://localhost/hello')173 expect(res).not.toBeNull()174 expect(res.status).toBe(200)175 expect(res.statusText).toBe('Hono is OK')176 expect(await res.text()).toBe('hello')177 })178179 it('GET httphello is ng', async () => {180 const res = await app.request('httphello')181 expect(res.status).toBe(404)182 })183184 it('GET /hello is ok', async () => {185 const res = await app.request('/hello')186 expect(res).not.toBeNull()187 expect(res.status).toBe(200)188 expect(res.statusText).toBe('Hono is OK')189 expect(await res.text()).toBe('hello')190 })191192 it('GET hello is ok', async () => {193 const res = await app.request('hello')194 expect(res).not.toBeNull()195 expect(res.status).toBe(200)196 expect(res.statusText).toBe('Hono is OK')197 expect(await res.text()).toBe('hello')198 })199200 it('GET /hello-with-shortcuts is ok', async () => {201 const res = await app.request('http://localhost/hello-with-shortcuts')202 expect(res).not.toBeNull()203 expect(res.status).toBe(201)204 expect(res.headers.get('X-Custom')).toBe('This is Hono')205 expect(res.headers.get('Content-Type')).toMatch(/text\/html/)206 expect(await res.text()).toBe('<h1>Hono!!!</h1>')207 })208209 it('GET / is not found', async () => {210 const res = await app.request('http://localhost/')211 expect(res).not.toBeNull()212 expect(res.status).toBe(404)213 })214215 it('GET /hello-env is ok', async () => {216 const res = await app.request('/hello-env', undefined, { HELLO: 'world' })217 expect(res.status).toBe(200)218 expect(await res.json()).toEqual({ HELLO: 'world' })219 })220221 it('GET /proxy-object is ok', async () => {222 const res = await app.request('/proxy-object')223 expect(res).not.toBeNull()224 expect(res.status).toBe(200)225 expect(await res.text()).toBe('proxy')226 })227228 it('GET /async-proxy-object is ok', async () => {229 const res = await app.request('/proxy-object')230 expect(res).not.toBeNull()231 expect(res.status).toBe(200)232 expect(await res.text()).toBe('proxy')233 })234 })235})236237describe('Register handlers without a path', () => {238 describe('No basePath', () => {239 const app = new Hono()240241 app.get((c) => {242 return c.text('Hello')243 })244245 it('GET http://localhost/ is ok', async () => {246 const res = await app.request('/')247 expect(res.status).toBe(200)248 expect(await res.text()).toBe('Hello')249 })250251 it('GET http://localhost/anything is not found', async () => {252 const res = await app.request('/anything')253 expect(res.status).toBe(404)254 })255 })256257 describe('With specifying basePath', () => {258 const app = new Hono().basePath('/about')259260 app.get((c) => {261 return c.text('About')262 })263264 it('GET http://localhost/about is ok', async () => {265 const res = await app.request('/about')266 expect(res.status).toBe(200)267 expect(await res.text()).toBe('About')268 })269270 it('GET http://localhost/ is not found', async () => {271 const res = await app.request('/')272 expect(res.status).toBe(404)273 })274 })275276 describe('With chaining', () => {277 const app = new Hono()278279 app.post('/books').get((c) => {280 return c.text('Books')281 })282283 it('GET http://localhost/books is ok', async () => {284 const res = await app.request('/books')285 expect(res.status).toBe(200)286 expect(await res.text()).toBe('Books')287 })288289 it('GET http://localhost/ is not found', async () => {290 const res = await app.request('/')291 expect(res.status).toBe(404)292 })293 })294})295296describe('Options', () => {297 describe('router option', () => {298 it('Should be SmartRouter', () => {299 const app = new Hono()300 expect(app.router instanceof SmartRouter).toBe(true)301 })302 it('Should be RegExpRouter', () => {303 const app = new Hono({304 router: new RegExpRouter(),305 })306 expect(app.router instanceof RegExpRouter).toBe(true)307 })308 })309310 describe('strict parameter', () => {311 describe('strict is true with not slash', () => {312 const app = new Hono()313314 app.get('/hello', (c) => {315 return c.text('/hello')316 })317318 it('/hello/ is not found', async () => {319 let res = await app.request('http://localhost/hello')320 expect(res).not.toBeNull()321 expect(res.status).toBe(200)322 res = await app.request('http://localhost/hello/')323 expect(res).not.toBeNull()324 expect(res.status).toBe(404)325 })326 })327328 describe('strict is true with slash', () => {329 const app = new Hono()330331 app.get('/hello/', (c) => {332 return c.text('/hello/')333 })334335 it('/hello is not found', async () => {336 let res = await app.request('http://localhost/hello/')337 expect(res).not.toBeNull()338 expect(res.status).toBe(200)339 res = await app.request('http://localhost/hello')340 expect(res).not.toBeNull()341 expect(res.status).toBe(404)342 })343 })344345 describe('strict is false', () => {346 const app = new Hono({ strict: false })347348 app.get('/hello', (c) => {349 return c.text('/hello')350 })351352 it('/hello and /hello/ are treated as the same', async () => {353 let res = await app.request('http://localhost/hello')354 expect(res).not.toBeNull()355 expect(res.status).toBe(200)356 res = await app.request('http://localhost/hello/')357 expect(res).not.toBeNull()358 expect(res.status).toBe(200)359 })360 })361362 describe('strict is false with `getPath` option', () => {363 const app = new Hono({364 strict: false,365 getPath: getPath,366 })367368 app.get('/hello', (c) => {369 return c.text('/hello')370 })371372 it('/hello and /hello/ are treated as the same', async () => {373 let res = await app.request('http://localhost/hello')374 expect(res).not.toBeNull()375 expect(res.status).toBe(200)376 res = await app.request('http://localhost/hello/')377 expect(res).not.toBeNull()378 expect(res.status).toBe(200)379 })380 })381 })382383 it('Should not modify the options passed to it', () => {384 const options = { strict: true }385 const clone = structuredClone(options)386 const app = new Hono(clone)387 expect(clone).toEqual(options)388 })389})390391describe('Destruct functions in context', () => {392 it('Should return 200 response - text', async () => {393 const app = new Hono()394 app.get('/text', ({ text }) => text('foo'))395 const res = await app.request('http://localhost/text')396 expect(res.status).toBe(200)397 })398 it('Should return 200 response - json', async () => {399 const app = new Hono()400 app.get('/json', ({ json }) => json({ foo: 'bar' }))401 const res = await app.request('http://localhost/json')402 expect(res.status).toBe(200)403 })404})405406describe('Routing', () => {407 it('Return it self', async () => {408 const app = new Hono()409410 const app2 = app.get('/', () => new Response('get /'))411 expect(app2).not.toBeUndefined()412 app2.delete('/', () => new Response('delete /'))413414 let res = await app2.request('http://localhost/', { method: 'GET' })415 expect(res).not.toBeNull()416 expect(res.status).toBe(200)417 expect(await res.text()).toBe('get /')418419 res = await app2.request('http://localhost/', { method: 'DELETE' })420 expect(res).not.toBeNull()421 expect(res.status).toBe(200)422 expect(await res.text()).toBe('delete /')423 })424425 it('Nested route', async () => {426 const app = new Hono()427428 const book = app.basePath('/book')429 book.get('/', (c) => c.text('get /book'))430 book.get('/:id', (c) => {431 return c.text('get /book/' + c.req.param('id'))432 })433 book.post('/', (c) => c.text('post /book'))434435 const user = app.basePath('/user')436 user.get('/login', (c) => c.text('get /user/login'))437 user.post('/register', (c) => c.text('post /user/register'))438439 const appForEachUser = user.basePath(':id')440 appForEachUser.get('/profile', (c) => c.text('get /user/' + c.req.param('id') + '/profile'))441442 app.get('/add-path-after-route-call', (c) => c.text('get /add-path-after-route-call'))443444 let res = await app.request('http://localhost/book', { method: 'GET' })445 expect(res.status).toBe(200)446 expect(await res.text()).toBe('get /book')447448 res = await app.request('http://localhost/book/123', { method: 'GET' })449 expect(res.status).toBe(200)450 expect(await res.text()).toBe('get /book/123')451452 res = await app.request('http://localhost/book', { method: 'POST' })453 expect(res.status).toBe(200)454 expect(await res.text()).toBe('post /book')455456 res = await app.request('http://localhost/book/', { method: 'GET' })457 expect(res.status).toBe(404)458459 res = await app.request('http://localhost/user/login', { method: 'GET' })460 expect(res.status).toBe(200)461 expect(await res.text()).toBe('get /user/login')462463 res = await app.request('http://localhost/user/register', { method: 'POST' })464 expect(res.status).toBe(200)465 expect(await res.text()).toBe('post /user/register')466467 res = await app.request('http://localhost/user/123/profile', { method: 'GET' })468 expect(res.status).toBe(200)469 expect(await res.text()).toBe('get /user/123/profile')470471 res = await app.request('http://localhost/add-path-after-route-call', { method: 'GET' })472 expect(res.status).toBe(200)473 expect(await res.text()).toBe('get /add-path-after-route-call')474 })475fix(trie-router): match suffix wildcard routes (#5236)Taku Amanobefore adoption63bbcf5
lines 476–489why, one step back476 it('Should match a suffix wildcard after falling back to TrieRouter', async () => {477 const app = new Hono()478 const sub = new Hono()479 sub.post('/items', (c) => c.text('items'))480 sub.post('/:slug', (c) => c.text('slug'))481 app.route('/api', sub)482 app.get('/assets*', (c) => c.text('asset'))483484 const res = await app.request('http://localhost/assets/app.js')485 expect(res.status).toBe(200)486 expect(await res.text()).toBe('asset')487 expect(app.router.name).toBe('SmartRouter + TrieRouter')488 })489Merge commit from forkYusuke Wadabefore adoptionf0b094d
lines 490–2095why, one step back490 it('Nested route - subApp with basePath', async () => {491 const app = new Hono()492 const book = new Hono().basePath('/book')493 book.get('/', (c) => c.text('get /book'))494 app.route('/api', book)495496 const res = await app.request('http://localhost/api/book', { method: 'GET' })497 expect(res.status).toBe(200)498 expect(await res.text()).toBe('get /book')499 })500501 describe('Nested route - basePath of the mounted routes', () => {502 it('Should set basePath to the mount path', () => {503 const app = new Hono()504 const sub = new Hono()505 sub.get('/posts/:id', (c) => c.text('post'))506 app.route('/:sub', sub)507508 expect(app.routes).toEqual([509 {510 basePath: '/:sub',511 method: 'GET',512 path: '/:sub/posts/:id',513 handler: expect.any(Function),514 },515 ])516 })517518 it('Should accumulate basePath through nested route() calls', () => {519 const app = new Hono()520 const sub1 = new Hono()521 const sub2 = new Hono()522 sub2.get('/posts/:id', (c) => c.text('post'))523 sub1.route('/:sub2', sub2)524 app.route('/:sub1', sub1)525526 expect(app.routes).toEqual([527 {528 basePath: '/:sub1/:sub2',529 method: 'GET',530 path: '/:sub1/:sub2/posts/:id',531 handler: expect.any(Function),532 },533 ])534 })535536 it('Should merge the basePath of a subApp created with basePath()', () => {537 const app = new Hono()538 const sub = new Hono().basePath('/book')539 sub.get('/:id', (c) => c.text('book'))540 app.route('/api', sub)541542 expect(app.routes).toEqual([543 {544 basePath: '/api/book',545 method: 'GET',546 path: '/api/book/:id',547 handler: expect.any(Function),548 },549 ])550 })551 })552553 it('Multiple route', async () => {554 const app = new Hono()555556 const book = new Hono()557 book.get('/hello', (c) => c.text('get /book/hello'))558559 const user = new Hono()560 user.get('/hello', (c) => c.text('get /user/hello'))561562 app.route('/book', book).route('/user', user)563564 let res = await app.request('http://localhost/book/hello', { method: 'GET' })565 expect(res.status).toBe(200)566 expect(await res.text()).toBe('get /book/hello')567568 res = await app.request('http://localhost/user/hello', { method: 'GET' })569 expect(res.status).toBe(200)570 expect(await res.text()).toBe('get /user/hello')571 })572573 describe('Nested route with middleware', () => {574 const api = new Hono()575 const api2 = api.use('*', async (_c, next) => await next())576577 it('Should mount routes with no type errors', () => {578 const app = new Hono().route('/api', api2)579 })580 })581582 describe('Grouped route', () => {583 let one: Hono, two: Hono, three: Hono584585 beforeEach(() => {586 one = new Hono()587 two = new Hono()588 three = new Hono()589 })590591 it('only works with correct order', async () => {592 three.get('/hi', (c) => c.text('hi'))593 two.route('/three', three)594 one.route('/two', two)595596 const { status } = await one.request('http://localhost/two/three/hi', { method: 'GET' })597 expect(status).toBe(200)598 })599600 it('fails with incorrect order 1', async () => {601 three.get('/hi', (c) => c.text('hi'))602 one.route('/two', two)603 two.route('/three', three)604605 const { status } = await one.request('http://localhost/two/three/hi', { method: 'GET' })606 expect(status).toBe(404)607 })608609 it('fails with incorrect order 2', async () => {610 two.route('/three', three)611 three.get('/hi', (c) => c.text('hi'))612 one.route('/two', two)613614 const { status } = await one.request('http://localhost/two/three/hi', { method: 'GET' })615 expect(status).toBe(404)616 })617618 it('fails with incorrect order 3', async () => {619 two.route('/three', three)620 one.route('/two', two)621 three.get('/hi', (c) => c.text('hi'))622623 const { status } = await one.request('http://localhost/two/three/hi', { method: 'GET' })624 expect(status).toBe(404)625 })626627 it('fails with incorrect order 4', async () => {628 one.route('/two', two)629 three.get('/hi', (c) => c.text('hi'))630 two.route('/three', three)631632 const { status } = await one.request('http://localhost/two/three/hi', { method: 'GET' })633 expect(status).toBe(404)634 })635636 it('fails with incorrect order 5', async () => {637 one.route('/two', two)638 two.route('/three', three)639 three.get('/hi', (c) => c.text('hi'))640641 const { status } = await one.request('http://localhost/two/three/hi', { method: 'GET' })642 expect(status).toBe(404)643 })644 })645646 it('routing with hostname', async () => {647 const app = new Hono({648 getPath: (req) => req.url.replace(/^https?:\/(.+?)$/, '$1'),649 })650651 const sub = new Hono()652 sub.get('/', (c) => c.text('hello sub'))653 sub.get('/foo', (c) => c.text('hello sub foo'))654655 app.get('/www1.example.com/hello', () => new Response('hello www1'))656 app.get('/www2.example.com/hello', () => new Response('hello www2'))657658 app.get('/www1.example.com/', (c) => c.text('hello www1 root'))659 app.route('/www1.example.com/sub', sub)660661 let res = await app.request('http://www1.example.com/hello')662 expect(res).not.toBeNull()663 expect(res.status).toBe(200)664 expect(await res.text()).toBe('hello www1')665666 res = await app.request('http://www2.example.com/hello')667 expect(res).not.toBeNull()668 expect(res.status).toBe(200)669 expect(await res.text()).toBe('hello www2')670671 res = await app.request('http://www1.example.com/')672 expect(res).not.toBeNull()673 expect(res.status).toBe(200)674 expect(await res.text()).toBe('hello www1 root')675676 res = await app.request('http://www1.example.com/sub')677 expect(res).not.toBeNull()678 expect(res.status).toBe(200)679 expect(await res.text()).toBe('hello sub')680681 res = await app.request('http://www1.example.com/sub/foo')682 expect(res).not.toBeNull()683 expect(res.status).toBe(200)684 expect(await res.text()).toBe('hello sub foo')685 })686687 it('routing with request header', async () => {688 const app = new Hono({689 getPath: (req) =>690 '/' + req.headers.get('host') + req.url.replace(/^https?:\/\/[^/]+(\/[^?]*)/, '$1'),691 })692693 const sub = new Hono()694 sub.get('/', (c) => c.text('hello sub'))695 sub.get('/foo', (c) => c.text('hello sub foo'))696697 app.get('/www1.example.com/hello', () => new Response('hello www1'))698 app.get('/www2.example.com/hello', () => new Response('hello www2'))699700 app.get('/www1.example.com/', (c) => c.text('hello www1 root'))701 app.route('/www1.example.com/sub', sub)702703 let res = await app.request('http://www1.example.com/hello', {704 headers: {705 host: 'www1.example.com',706 },707 })708 expect(res).not.toBeNull()709 expect(res.status).toBe(200)710 expect(await res.text()).toBe('hello www1')711712 res = await app.request('http://www2.example.com/hello', {713 headers: {714 host: 'www2.example.com',715 },716 })717 expect(res).not.toBeNull()718 expect(res.status).toBe(200)719 expect(await res.text()).toBe('hello www2')720721 res = await app.request('http://www1.example.com/', {722 headers: {723 host: 'www1.example.com',724 },725 })726 expect(res).not.toBeNull()727 expect(res.status).toBe(200)728 expect(await res.text()).toBe('hello www1 root')729730 res = await app.request('http://www1.example.com/sub', {731 headers: {732 host: 'www1.example.com',733 },734 })735 expect(res).not.toBeNull()736 expect(res.status).toBe(200)737 expect(await res.text()).toBe('hello sub')738739 res = await app.request('http://www1.example.com/sub/foo', {740 headers: {741 host: 'www1.example.com',742 },743 })744 expect(res).not.toBeNull()745 expect(res.status).toBe(200)746 expect(await res.text()).toBe('hello sub foo')747 expect(res.status).toBe(200)748 })749750 describe('routing with the bindings value', () => {751 const app = new Hono<{ Bindings: { host: string } }>({752 getPath: (req, options) => {753 const url = new URL(req.url)754 const host = options?.env?.host755 const prefix = url.host === host ? '/FOO' : ''756 return url.pathname === '/' ? prefix : `${prefix}${url.pathname}`757 },758 })759760 app.get('/about', (c) => c.text('About root'))761 app.get('/FOO/about', (c) => c.text('About FOO'))762763 it('Should return 200 without specifying a hostname', async () => {764 const res = await app.request('/about')765 expect(res.status).toBe(200)766 expect(await res.text()).toBe('About root')767 })768769 it('Should return 200 with specifying the hostname in env', async () => {770 const req = new Request('http://foo.localhost/about')771 const res = await app.fetch(req, { host: 'foo.localhost' })772 expect(res.status).toBe(200)773 expect(await res.text()).toBe('About FOO')774 })775 })776777 describe('Chained route', () => {778 const app = new Hono()779780 app781 .get('/chained/:abc', (c) => {782 const abc = c.req.param('abc')783 return c.text(`GET for ${abc}`)784 })785 .post((c) => {786 const abc = c.req.param('abc')787 return c.text(`POST for ${abc}`)788 })789 it('Should return 200 response from GET request', async () => {790 const res = await app.request('http://localhost/chained/abc', { method: 'GET' })791 expect(res.status).toBe(200)792 expect(await res.text()).toBe('GET for abc')793 })794 it('Should return 200 response from POST request', async () => {795 const res = await app.request('http://localhost/chained/abc', { method: 'POST' })796 expect(res.status).toBe(200)797 expect(await res.text()).toBe('POST for abc')798 })799 it('Should return 404 response from PUT request', async () => {800 const res = await app.request('http://localhost/chained/abc', { method: 'PUT' })801 expect(res.status).toBe(404)802 })803 })804805 describe('Encoded path', () => {806 let app: Hono807 beforeEach(() => {808 app = new Hono()809 })810811 it('should decode path parameter', async () => {812 app.get('/users/:id', (c) => c.text(`id is ${c.req.param('id')}`))813814 const res = await app.request('http://localhost/users/%C3%A7awa%20y%C3%AE%3F')815 expect(res.status).toBe(200)816 expect(await res.text()).toBe('id is çawa yî?')817 })818819 it('should decode "/"', async () => {820 app.get('/users/:id', (c) => c.text(`id is ${c.req.param('id')}`))821822 const res = await app.request('http://localhost/users/hono%2Fposts') // %2F is '/'823 expect(res.status).toBe(200)824 expect(await res.text()).toBe('id is hono/posts')825 })826827 it('should decode alphabets', async () => {828 app.get('/users/static', (c) => c.text('static'))829830 const res = await app.request('http://localhost/users/%73tatic') // %73 is 's'831 expect(res.status).toBe(200)832 expect(await res.text()).toBe('static')833 })834835 it('should decode alphabets with invalid UTF-8 sequence', async () => {836 app.get('/static/:path', (c) => {837 return c.text(`by c.req.param: ${c.req.param('path')}`)838 })839840 const res = await app.request('http://localhost/%73tatic/%A4%A2') // %73 is 's', %A4%A2 is invalid UTF-8 sequence841 expect(res.status).toBe(200)842 expect(await res.text()).toBe('by c.req.param: %A4%A2')843 })844845 it('should decode alphabets with invalid percent encoding', async () => {846 app.get('/static/:path', (c) => {847 return c.text(`by c.req.param: ${c.req.param('path')}`)848 })849850 const res = await app.request('http://localhost/%73tatic/%a') // %73 is 's', %a is invalid percent encoding851 expect(res.status).toBe(200)852 expect(await res.text()).toBe('by c.req.param: %a')853 })854855 it('should not double decode', async () => {856 app.get('/users/:id', (c) => c.text(`posts of ${c.req.param('id')}`))857858 const res = await app.request('http://localhost/users/%2525') // %25 is '%'859 expect(res.status).toBe(200)860 expect(await res.text()).toBe('posts of %25')861 })862 })863})864865describe('param and query', () => {866 const apps: Record<string, Hono> = {}867 apps['get by name'] = (() => {868 const app = new Hono()869870 app.get('/entry/:id', (c) => {871 const id = c.req.param('id')872 return c.text(`id is ${id}`)873 })874875 app.get('/date/:date{[0-9]+}', (c) => {876 const date = c.req.param('date')877 return c.text(`date is ${date}`)878 })879880 app.get('/search', (c) => {881 const name = c.req.query('name')882 return c.text(`name is ${name}`)883 })884885 app.get('/multiple-values', (c) => {886 const queries = c.req.queries('q') ?? throwExpression('missing query values')887 const limit = c.req.queries('limit') ?? throwExpression('missing query values')888 return c.text(`q is ${queries[0]} and ${queries[1]}, limit is ${limit[0]}`)889 })890891 app.get('/add-header', (c) => {892 const bar = c.req.header('X-Foo')893 return c.text(`foo is ${bar}`)894 })895896 return app897 })()898899 apps['get all as an object'] = (() => {900 const app = new Hono()901902 app.get('/entry/:id', (c) => {903 const { id } = c.req.param()904 return c.text(`id is ${id}`)905 })906907 app.get('/date/:date{[0-9]+}', (c) => {908 const { date } = c.req.param()909 return c.text(`date is ${date}`)910 })911912 app.get('/search', (c) => {913 const { name } = c.req.query()914 return c.text(`name is ${name}`)915 })916917 app.get('/multiple-values', (c) => {918 const { q, limit } = c.req.queries()919 return c.text(`q is ${q[0]} and ${q[1]}, limit is ${limit[0]}`)920 })921922 app.get('/add-header', (c) => {923 const { 'x-foo': bar } = c.req.header()924 return c.text(`foo is ${bar}`)925 })926927 return app928 })()929930 describe.each(Object.keys(apps))('%s', (name) => {931 const app = apps[name]932933 it('param of /entry/:id is found', async () => {934 const res = await app.request('http://localhost/entry/123')935 expect(res.status).toBe(200)936 expect(await res.text()).toBe('id is 123')937 })938939 it('param of /entry/:id is found, even for Array object method names', async () => {940 const res = await app.request('http://localhost/entry/key')941 expect(res.status).toBe(200)942 expect(await res.text()).toBe('id is key')943 })944945 it('param of /entry/:id is decoded', async () => {946 const res = await app.request('http://localhost/entry/%C3%A7awa%20y%C3%AE%3F')947 expect(res.status).toBe(200)948 expect(await res.text()).toBe('id is çawa yî?')949 })950951 it('param of /date/:date is found', async () => {952 const res = await app.request('http://localhost/date/0401')953 expect(res.status).toBe(200)954 expect(await res.text()).toBe('date is 0401')955 })956957 it('query of /search?name=sam is found', async () => {958 const res = await app.request('http://localhost/search?name=sam')959 expect(res.status).toBe(200)960 expect(await res.text()).toBe('name is sam')961 })962963 it('query of /search?name=sam&name=tom is found', async () => {964 const res = await app.request('http://localhost/search?name=sam&name=tom')965 expect(res.status).toBe(200)966 expect(await res.text()).toBe('name is sam')967 })968969 it('query of /multiple-values?q=foo&q=bar&limit=10 is found', async () => {970 const res = await app.request('http://localhost/multiple-values?q=foo&q=bar&limit=10')971 expect(res.status).toBe(200)972 expect(await res.text()).toBe('q is foo and bar, limit is 10')973 })974975 it('/add-header header - X-Foo is Bar', async () => {976 const req = new Request('http://localhost/add-header')977 req.headers.append('X-Foo', 'Bar')978 const res = await app.request(req)979 expect(res.status).toBe(200)980 expect(await res.text()).toBe('foo is Bar')981 })982 })983984 describe('param with undefined', () => {985 const app = new Hono()986 app.get('/foo/:foo', (c) => {987 const bar = c.req.param('bar')988 return c.json({ foo: bar })989 })990 it('param of /foo/foo should return undefined not "undefined"', async () => {991 const res = await app.request('http://localhost/foo/foo')992 expect(res.status).toBe(200)993 expect(await res.json()).toEqual({ foo: undefined })994 })995 })996})997998describe('c.req.path', () => {999 const app = new Hono()1000 app.get('/', (c) => c.text(c.req.path))1001 app.get('/search', (c) => c.text(c.req.path))10021003 it('Should get the path `/` correctly', async () => {1004 const res = await app.request('/')1005 expect(res.status).toBe(200)1006 expect(await res.text()).toBe('/')1007 })10081009 it('Should get the path `/search` correctly with a query', async () => {1010 const res = await app.request('/search?query=hono')1011 expect(res.status).toBe(200)1012 expect(await res.text()).toBe('/search')1013 })1014})10151016describe('Header', () => {1017 const app = new Hono()10181019 app.get('/text', (c) => {1020 return c.text('Hello')1021 })10221023 app.get('/text-with-custom-header', (c) => {1024 c.header('X-Custom', 'Message')1025 return c.text('Hello')1026 })10271028 it('Should return correct headers - /text', async () => {1029 const res = await app.request('/text')1030 expect(res.status).toBe(200)1031 expect(res.headers.get('content-type')).toMatch(/^text\/plain/)1032 expect(await res.text()).toBe('Hello')1033 })10341035 it('Should return correct headers - /text-with-custom-header', async () => {1036 const res = await app.request('/text-with-custom-header')1037 expect(res.status).toBe(200)1038 expect(res.headers.get('x-custom')).toBe('Message')1039 expect(res.headers.get('content-type')).toMatch(/^text\/plain/)1040 expect(await res.text()).toBe('Hello')1041 })1042})10431044describe('Middleware', () => {1045 describe('Basic', () => {1046 const app = new Hono()10471048 // Custom Logger1049 app.use('*', async (c, next) => {1050 console.log(`${c.req.method} : ${c.req.url}`)1051 await next()1052 })10531054 // Append Custom Header1055 app.use('*', async (c, next) => {1056 await next()1057 c.res.headers.append('x-custom', 'root')1058 })10591060 app.use('/hello', async (c, next) => {1061 await next()1062 c.res.headers.append('x-message', 'custom-header')1063 })10641065 app.use('/hello/*', async (c, next) => {1066 await next()1067 c.res.headers.append('x-message-2', 'custom-header-2')1068 })10691070 app.get('/hello', (c) => {1071 return c.text('hello')1072 })10731074 app.use('/json/*', async (c, next) => {1075 c.res.headers.append('foo', 'bar')1076 await next()1077 })10781079 app.get('/json', (c) => {1080 // With a raw response1081 return new Response(1082 JSON.stringify({1083 message: 'hello',1084 }),1085 {1086 headers: {1087 'content-type': 'application/json',1088 },1089 }1090 )1091 })10921093 app.get('/hello/:message', (c) => {1094 const message = c.req.param('message')1095 return c.text(`${message}`)1096 })10971098 app.get('/error', () => {1099 throw new Error('Error!')1100 })11011102 app.notFound((c) => {1103 return c.text('Not Found Foo', 404)1104 })11051106 it('logging and custom header', async () => {1107 const res = await app.request('http://localhost/hello')1108 expect(res.status).toBe(200)1109 expect(await res.text()).toBe('hello')1110 expect(res.headers.get('x-custom')).toBe('root')1111 expect(res.headers.get('x-message')).toBe('custom-header')1112 expect(res.headers.get('x-message-2')).toBe('custom-header-2')1113 })11141115 it('logging and custom header with named param', async () => {1116 const res = await app.request('http://localhost/hello/message')1117 expect(res.status).toBe(200)1118 expect(await res.text()).toBe('message')1119 expect(res.headers.get('x-custom')).toBe('root')1120 expect(res.headers.get('x-message-2')).toBe('custom-header-2')1121 })11221123 it('should return correct the content-type header', async () => {1124 const res = await app.request('http://localhost/json')1125 expect(res.status).toBe(200)1126 expect(res.headers.get('content-type')).toMatch(/^application\/json/)1127 })11281129 it('not found', async () => {1130 const res = await app.request('http://localhost/foo')1131 expect(res.status).toBe(404)1132 expect(await res.text()).toBe('Not Found Foo')1133 })11341135 it('internal server error', async () => {1136 const res = await app.request('http://localhost/error')1137 expect(res.status).toBe(500)1138 console.log(await res.text())1139 })1140 })11411142 describe('Chained route', () => {1143 const app = new Hono()1144 app1145 .use('/chained/*', async (c, next) => {1146 c.req.raw.headers.append('x-before', 'abc')1147 await next()1148 })1149 .use(async (c, next) => {1150 await next()1151 c.header(1152 'x-after',1153 c.req.header('x-before') ?? throwExpression('missing `x-before` header')1154 )1155 })1156 .get('/chained/abc', (c) => {1157 return c.text('GET chained')1158 })1159 it('GET /chained/abc', async () => {1160 const res = await app.request('http://localhost/chained/abc')1161 expect(res.status).toBe(200)1162 expect(await res.text()).toBe('GET chained')1163 expect(res.headers.get('x-after')).toBe('abc')1164 })1165 })11661167 describe('Multiple handler', () => {1168 const app = new Hono()1169 app1170 .use(1171 '/multiple/*',1172 async (c, next) => {1173 c.req.raw.headers.append('x-before', 'abc')1174 await next()1175 },1176 async (c, next) => {1177 await next()1178 c.header(1179 'x-after',1180 c.req.header('x-before') ?? throwExpression('missing `x-before` header')1181 )1182 }1183 )1184 .get('/multiple/abc', (c) => {1185 return c.text('GET multiple')1186 })1187 it('GET /multiple/abc', async () => {1188 const res = await app.request('http://localhost/multiple/abc')1189 expect(res.status).toBe(200)1190 expect(await res.text()).toBe('GET multiple')1191 expect(res.headers.get('x-after')).toBe('abc')1192 })1193 })11941195 describe('Overwrite the response from middleware after next()', () => {1196 const app = new Hono()11971198 app.use('/normal', async (c, next) => {1199 await next()1200 c.res = new Response('Middleware')1201 })12021203 app.use('/overwrite', async (c, next) => {1204 await next()1205 c.res = undefined1206 c.res = new Response('Middleware')1207 })12081209 app.get('*', (c) => {1210 c.header('x-custom', 'foo')1211 return c.text('Handler')1212 })12131214 it('Should have the custom header', async () => {1215 const res = await app.request('/normal')1216 expect(res.headers.get('x-custom')).toBe('foo')1217 })12181219 it('Should not have the custom header', async () => {1220 const res = await app.request('/overwrite')1221 expect(res.headers.get('x-custom')).toBe(null)1222 })1223 })1224})12251226describe('Builtin Middleware', () => {1227 const app = new Hono()1228 app.use('/abc', poweredBy())1229 app.use('/def', async (c, next) => {1230 const middleware = poweredBy()1231 await middleware(c, next)1232 })1233 app.get('/abc', () => new Response())1234 app.get('/def', () => new Response())12351236 it('"powered-by" middleware', async () => {1237 const res = await app.request('http://localhost/abc')1238 expect(res.headers.get('x-powered-by')).toBe('Hono')1239 })12401241 it('"powered-by" middleware in a handler', async () => {1242 const res = await app.request('http://localhost/def')1243 expect(res.headers.get('x-powered-by')).toBe('Hono')1244 })1245})12461247describe('Middleware with app.HTTP_METHOD', () => {1248 describe('Basic', () => {1249 const app = new Hono()12501251 app.all('*', async (c, next) => {1252 c.header('x-before-dispatch', 'foo')1253 await next()1254 c.header('x-custom-message', 'hello')1255 })12561257 const customHeader = async (c: Context, next: Next) => {1258 c.req.raw.headers.append('x-custom-foo', 'bar')1259 await next()1260 }12611262 const customHeader2 = async (c: Context, next: Next) => {1263 await next()1264 c.header('x-custom-foo-2', 'bar-2')1265 }12661267 app1268 .get('/abc', customHeader, (c) => {1269 const foo = c.req.header('x-custom-foo') || ''1270 return c.text(foo)1271 })1272 .post(customHeader2, (c) => {1273 return c.text('POST /abc')1274 })12751276 it('GET /abc', async () => {1277 const res = await app.request('http://localhost/abc')1278 expect(res.status).toBe(200)1279 expect(res.headers.get('x-custom-message')).toBe('hello')1280 expect(res.headers.get('x-before-dispatch')).toBe('foo')1281 expect(await res.text()).toBe('bar')1282 })1283 it('POST /abc', async () => {1284 const res = await app.request('http://localhost/abc', { method: 'POST' })1285 expect(res.status).toBe(200)1286 expect(await res.text()).toBe('POST /abc')1287 expect(res.headers.get('x-custom-foo-2')).toBe('bar-2')1288 })1289 })12901291 describe('With builtin middleware', () => {1292 const app = new Hono()1293 app.get('/abc', poweredBy(), (c) => {1294 return c.text('GET /abc')1295 })1296 it('GET /abc', async () => {1297 const res = await app.request('http://localhost/abc')1298 expect(res.status).toBe(200)1299 expect(await res.text()).toBe('GET /abc')1300 expect(res.headers.get('x-powered-by')).toBe('Hono')1301 })1302 })1303})13041305describe('Not Found', () => {1306 const app = new Hono()13071308 app.notFound((c) => {1309 return c.text('Custom 404 Not Found', 404)1310 })13111312 app.get('/hello', (c) => {1313 return c.text('hello')1314 })13151316 app.get('/notfound', (c) => {1317 return c.notFound()1318 })13191320 it('Custom 404 Not Found', async () => {1321 let res = await app.request('http://localhost/hello')1322 expect(res.status).toBe(200)1323 res = await app.request('http://localhost/notfound')1324 expect(res.status).toBe(404)1325 res = await app.request('http://localhost/foo')1326 expect(res.status).toBe(404)1327 expect(await res.text()).toBe('Custom 404 Not Found')1328 })13291330 describe('Not Found with a middleware', () => {1331 const app = new Hono()13321333 app.get('/', (c) => c.text('hello'))1334 app.use('*', async (c, next) => {1335 await next()1336 c.res = new Response((await c.res.text()) + ' + Middleware', c.res)1337 })13381339 it('Custom 404 Not Found', async () => {1340 let res = await app.request('http://localhost/')1341 expect(res.status).toBe(200)1342 expect(await res.text()).toBe('hello')1343 res = await app.request('http://localhost/foo')1344 expect(res.status).toBe(404)1345 expect(await res.text()).toBe('404 Not Found + Middleware')1346 })1347 })13481349 describe('Not Found with some middleware', () => {1350 const app = new Hono()13511352 app.get('/', (c) => c.text('hello'))1353 app.use('*', async (c, next) => {1354 await next()1355 c.res = new Response((await c.res.text()) + ' + Middleware 1', c.res)1356 })1357 app.use('*', async (c, next) => {1358 await next()1359 c.res = new Response((await c.res.text()) + ' + Middleware 2', c.res)1360 })13611362 it('Custom 404 Not Found', async () => {1363 let res = await app.request('http://localhost/')1364 expect(res.status).toBe(200)1365 expect(await res.text()).toBe('hello')1366 res = await app.request('http://localhost/foo')1367 expect(res.status).toBe(404)1368 expect(await res.text()).toBe('404 Not Found + Middleware 2 + Middleware 1')1369 })1370 })13711372 describe('No response from a handler', () => {1373 const app = new Hono()13741375 app.get('/', (c) => c.text('hello'))1376 app.get('/not-found', async (c) => undefined)13771378 it('Custom 404 Not Found', async () => {1379 let res = await app.request('http://localhost/')1380 expect(res.status).toBe(200)1381 expect(await res.text()).toBe('hello')1382 res = await app.request('http://localhost/not-found')1383 expect(res.status).toBe(404)1384 expect(await res.text()).toBe('404 Not Found')1385 })1386 })13871388 describe('Custom 404 Not Found with a middleware like Compress Middleware', () => {1389 const app = new Hono()13901391 // Custom Middleware which creates a new Response object after `next()`.1392 app.use('*', async (c, next) => {1393 await next()1394 c.res = new Response(await c.res.text(), c.res)1395 })13961397 app.notFound((c) => {1398 return c.text('Custom NotFound', 404)1399 })14001401 it('Custom 404 Not Found', async () => {1402 const res = await app.request('http://localhost/')1403 expect(res.status).toBe(404)1404 expect(await res.text()).toBe('Custom NotFound')1405 })1406 })1407})14081409describe('Redirect', () => {1410 const app = new Hono()1411 app.get('/redirect', (c) => {1412 return c.redirect('/')1413 })14141415 it('Absolute URL', async () => {1416 const res = await app.request('https://example.com/redirect')1417 expect(res.status).toBe(302)1418 expect(res.headers.get('Location')).toBe('/')1419 })1420})14211422describe('Error handle', () => {1423 describe('Basic', () => {1424 const app = new Hono()14251426 app.get('/error', () => {1427 throw new Error('This is Error')1428 })14291430 app.get('/error-string', () => {1431 throw 'This is Error'1432 })14331434 app.use('/error-middleware', async () => {1435 throw new Error('This is Middleware Error')1436 })14371438 app.onError((err, c) => {1439 c.header('x-debug', err.message)1440 return c.text('Custom Error Message', 500)1441 })14421443 it('Should throw Error if a non-Error object is thrown in a handler', async () => {1444 expect(() => app.request('/error-string')).toThrowError()1445 })14461447 it('Custom Error Message', async () => {1448 let res = await app.request('https://example.com/error')1449 expect(res.status).toBe(500)1450 expect(await res.text()).toBe('Custom Error Message')1451 expect(res.headers.get('x-debug')).toBe('This is Error')14521453 res = await app.request('https://example.com/error-middleware')1454 expect(res.status).toBe(500)1455 expect(await res.text()).toBe('Custom Error Message')1456 expect(res.headers.get('x-debug')).toBe('This is Middleware Error')1457 })1458 })14591460 describe('Async custom handler', () => {1461 const app = new Hono()14621463 app.get('/error', () => {1464 throw new Error('This is Error')1465 })14661467 app.use('/error-middleware', async () => {1468 throw new Error('This is Middleware Error')1469 })14701471 app.onError(async (err, c) => {1472 const promise = new Promise((resolve) =>1473 setTimeout(() => {1474 resolve('Promised')1475 }, 1)1476 )1477 const message = (await promise) as string1478 c.header('x-debug', err.message)1479 return c.text(`Custom Error Message with ${message}`, 500)1480 })14811482 it('Custom Error Message', async () => {1483 let res = await app.request('https://example.com/error')1484 expect(res.status).toBe(500)1485 expect(await res.text()).toBe('Custom Error Message with Promised')1486 expect(res.headers.get('x-debug')).toBe('This is Error')14871488 res = await app.request('https://example.com/error-middleware')1489 expect(res.status).toBe(500)1490 expect(await res.text()).toBe('Custom Error Message with Promised')1491 expect(res.headers.get('x-debug')).toBe('This is Middleware Error')1492 })1493 })14941495 describe('Handle HTTPException', () => {1496 const app = new Hono()14971498 app.get('/exception', () => {1499 throw new HTTPException(401, {1500 message: 'Unauthorized',1501 })1502 })15031504 it('Should return 401 response', async () => {1505 const res = await app.request('http://localhost/exception')1506 expect(res.status).toBe(401)1507 expect(await res.text()).toBe('Unauthorized')1508 })15091510 const app2 = new Hono()15111512 app2.get('/exception', () => {1513 throw new HTTPException(401)1514 })15151516 app2.onError((err, c) => {1517 if (err instanceof HTTPException && err.status === 401) {1518 return c.text('Custom Error Message', 401)1519 }1520 return c.text('Internal Server Error', 500)1521 })15221523 it('Should return 401 response with a custom message', async () => {1524 const res = await app2.request('http://localhost/exception')1525 expect(res.status).toBe(401)1526 expect(await res.text()).toBe('Custom Error Message')1527 })1528 })15291530 describe('Handle HTTPException like object', () => {1531 const app = new Hono()15321533 class CustomError extends Error {1534 getResponse() {1535 return new Response('Custom Error', { status: 400 })1536 }1537 }15381539 app.get('/exception', () => {1540 throw new CustomError()1541 })15421543 it('Should return 401 response', async () => {1544 const res = await app.request('http://localhost/exception')1545 expect(res.status).toBe(400)1546 expect(await res.text()).toBe('Custom Error')1547 })1548 })15491550 describe('HTTPException with finally block', () => {1551 const app = new Hono()1552 app.use(async (c) => {1553 try {1554 throw new Error()1555 } catch (cause) {1556 throw new HTTPException(302, {1557 cause,1558 res: c.redirect('/?error=invalid_request', 302),1559 })1560 } finally {1561 c.header('x-custom', 'custom message')1562 }1563 })1564 it('Should have the custom header', async () => {1565 const res = await app.request('http://localhost/')1566 expect(res.status).toBe(302)1567 expect(res.headers.get('x-custom')).toBe('custom message')1568 })1569 })1570})15711572describe('Error handling in middleware', () => {1573 const app = new Hono()15741575 app.get('/handle-error-in-middleware', async (c, next) => {1576 await next()1577 if (c.error) {1578 const message = c.error.message1579 c.res = c.text(`Handle the error in middleware, original message is ${message}`, 500)1580 }1581 })15821583 app.get('/handle-error-in-middleware-async', async (c, next) => {1584 await next()1585 if (c.error) {1586 const message = c.error.message1587 c.res = c.text(1588 `Handle the error in middleware with async, original message is ${message}`,1589 5001590 )1591 }1592 })15931594 app.get('/handle-error-in-middleware', () => {1595 throw new Error('Error message')1596 })15971598 app.get('/handle-error-in-middleware-async', async () => {1599 throw new Error('Error message')1600 })16011602 it('Should handle the error in middleware', async () => {1603 const res = await app.request('https://example.com/handle-error-in-middleware')1604 expect(res.status).toBe(500)1605 expect(await res.text()).toBe(1606 'Handle the error in middleware, original message is Error message'1607 )1608 })16091610 it('Should handle the error in middleware - async', async () => {1611 const res = await app.request('https://example.com/handle-error-in-middleware-async')1612 expect(res.status).toBe(500)1613 expect(await res.text()).toBe(1614 'Handle the error in middleware with async, original message is Error message'1615 )1616 })16171618 describe('Default route app.use', () => {1619 const app = new Hono()1620 app1621 .use(async (c, next) => {1622 c.header('x-default-use', 'abc')1623 await next()1624 })1625 .get('/multiple/abc', (c) => {1626 return c.text('GET multiple')1627 })1628 it('GET /multiple/abc', async () => {1629 const res = await app.request('http://localhost/multiple/abc')1630 expect(res.status).toBe(200)1631 expect(await res.text()).toBe('GET multiple')1632 expect(res.headers.get('x-default-use')).toBe('abc')1633 })1634 })16351636 describe('Error in `notFound()`', () => {1637 const app = new Hono()16381639 app.use('*', async () => {})16401641 app.notFound(() => {1642 throw new Error('Error in Not Found')1643 })16441645 app.onError((err, c) => {1646 return c.text(err.message, 400)1647 })16481649 it('Should handle the error thrown in `notFound()``', async () => {1650 const res = await app.request('http://localhost/')1651 expect(res.status).toBe(400)1652 expect(await res.text()).toBe('Error in Not Found')1653 })1654 })1655})16561657describe('Request methods with custom middleware', () => {1658 const app = new Hono()16591660 app.use('*', async (c, next) => {1661 const query = c.req.query('foo')16621663 // @ts-ignore1664 const param = c.req.param('foo') // This will cause a type error.1665 const header = c.req.header('User-Agent')1666 await next()1667 c.header('X-Query-2', query ?? throwExpression('missing `X-Query-2` header'))1668 c.header('X-Param-2', param)1669 c.header('X-Header-2', header ?? throwExpression('missing `X-Header-2` header'))1670 })16711672 app.get('/:foo', (c) => {1673 const query = c.req.query('foo')1674 const param = c.req.param('foo')1675 const header = c.req.header('User-Agent')1676 c.header('X-Query', query ?? throwExpression('missing `X-Query` header'))1677 c.header('X-Param', param)1678 c.header('X-Header', header ?? throwExpression('missing `X-Header` header'))1679 return c.body('Hono')1680 })16811682 it('query', async () => {1683 const url = new URL('http://localhost/bar')1684 url.searchParams.append('foo', 'bar')1685 const req = new Request(url.toString())1686 req.headers.append('User-Agent', 'bar')1687 const res = await app.request(req)16881689 expect(res.status).toBe(200)1690 expect(res.headers.get('X-Query')).toBe('bar')1691 expect(res.headers.get('X-Param')).toBe('bar')1692 expect(res.headers.get('X-Header')).toBe('bar')16931694 expect(res.headers.get('X-Query-2')).toBe('bar')1695 expect(res.headers.get('X-Param-2')).toBe(null)1696 expect(res.headers.get('X-Header-2')).toBe('bar')1697 })1698})16991700describe('Middleware + c.json(0, requestInit)', () => {1701 const app = new Hono()1702 app.use('/', async (c, next) => {1703 await next()1704 })1705 app.get('/', (c) => {1706 return c.json(0, {1707 status: 200,1708 headers: {1709 foo: 'bar',1710 },1711 })1712 })1713 it('Should return a correct headers', async () => {1714 const res = await app.request('/')1715 expect(res.headers.get('content-type')).toMatch(/^application\/json/)1716 expect(res.headers.get('foo')).toBe('bar')1717 })1718})17191720describe('Hono with `app.route`', () => {1721 describe('Basic', () => {1722 const app = new Hono()1723 const api = new Hono()1724 const middleware = new Hono()17251726 api.use('*', async (c, next) => {1727 await next()1728 c.res.headers.append('x-custom-a', 'a')1729 })17301731 api.get('/posts', (c) => c.text('List'))1732 api.post('/posts', (c) => c.text('Create'))1733 api.get('/posts/:id', (c) => c.text(`GET ${c.req.param('id')}`))17341735 middleware.use('*', async (c, next) => {1736 await next()1737 c.res.headers.append('x-custom-b', 'b')1738 })17391740 app.route('/api', middleware)1741 app.route('/api', api)17421743 app.get('/foo', (c) => c.text('bar'))17441745 it('Should return not found response', async () => {1746 const res = await app.request('http://localhost/')1747 expect(res.status).toBe(404)1748 })17491750 it('Should return not found response', async () => {1751 const res = await app.request('http://localhost/posts')1752 expect(res.status).toBe(404)1753 })17541755 test('GET /api/posts', async () => {1756 const res = await app.request('http://localhost/api/posts')1757 expect(res.status).toBe(200)1758 expect(await res.text()).toBe('List')1759 })17601761 test('Custom header by middleware', async () => {1762 const res = await app.request('http://localhost/api/posts')1763 expect(res.status).toBe(200)1764 expect(res.headers.get('x-custom-a')).toBe('a')1765 expect(res.headers.get('x-custom-b')).toBe('b')1766 })17671768 test('POST /api/posts', async () => {1769 const res = await app.request('http://localhost/api/posts', { method: 'POST' })1770 expect(res.status).toBe(200)1771 expect(await res.text()).toBe('Create')1772 })17731774 test('GET /api/posts/123', async () => {1775 const res = await app.request('http://localhost/api/posts/123')1776 expect(res.status).toBe(200)1777 expect(await res.text()).toBe('GET 123')1778 })17791780 test('GET /foo', async () => {1781 const res = await app.request('http://localhost/foo')1782 expect(res.status).toBe(200)1783 expect(await res.text()).toBe('bar')1784 })17851786 describe('With app.get(...handler)', () => {1787 const app = new Hono()1788 const about = new Hono()1789 about.get((c) => c.text('me'))1790 const subApp = new Hono()1791 subApp.route('/about', about)1792 app.route('/', subApp)17931794 it('Should return 200 response - /about', async () => {1795 const res = await app.request('/about')1796 expect(res.status).toBe(200)1797 expect(await res.text()).toBe('me')1798 })17991800 test('Should return 404 response /about/foo', async () => {1801 const res = await app.request('/about/foo')1802 expect(res.status).toBe(404)1803 })1804 })18051806 describe('With app.get(...handler) and app.basePath()', () => {1807 const app = new Hono()1808 const about = new Hono().basePath('/about')1809 about.get((c) => c.text('me'))1810 app.route('/', about)18111812 it('Should return 200 response - /about', async () => {1813 const res = await app.request('/about')1814 expect(res.status).toBe(200)1815 expect(await res.text()).toBe('me')1816 })18171818 test('Should return 404 response /about/foo', async () => {1819 const res = await app.request('/about/foo')1820 expect(res.status).toBe(404)1821 })1822 })1823 })18241825 describe('Chaining', () => {1826 const app = new Hono()1827 const route = new Hono()1828 route.get('/post', (c) => c.text('GET /POST v2')).post((c) => c.text('POST /POST v2'))1829 app.route('/v2', route)18301831 it('Should return 200 response - GET /v2/post', async () => {1832 const res = await app.request('http://localhost/v2/post')1833 expect(res.status).toBe(200)1834 expect(await res.text()).toBe('GET /POST v2')1835 })18361837 it('Should return 200 response - POST /v2/post', async () => {1838 const res = await app.request('http://localhost/v2/post', { method: 'POST' })1839 expect(res.status).toBe(200)1840 expect(await res.text()).toBe('POST /POST v2')1841 })18421843 it('Should return 404 response - DELETE /v2/post', async () => {1844 const res = await app.request('http://localhost/v2/post', { method: 'DELETE' })1845 expect(res.status).toBe(404)1846 })1847 })18481849 describe('Nested', () => {1850 const app = new Hono()1851 const api = new Hono()1852 const book = new Hono()18531854 book.get('/', (c) => c.text('list books'))1855 book.get('/:id', (c) => c.text(`book ${c.req.param('id')}`))18561857 api.get('/', (c) => c.text('this is API'))1858 api.route('/book', book)18591860 app.get('/', (c) => c.text('root'))1861 app.route('/v2', api)18621863 it('Should return 200 response - GET /', async () => {1864 const res = await app.request('http://localhost/')1865 expect(res.status).toBe(200)1866 expect(await res.text()).toBe('root')1867 })18681869 it('Should return 200 response - GET /v2', async () => {1870 const res = await app.request('http://localhost/v2')1871 expect(res.status).toBe(200)1872 expect(await res.text()).toBe('this is API')1873 })18741875 it('Should return 200 response - GET /v2/book', async () => {1876 const res = await app.request('http://localhost/v2/book')1877 expect(res.status).toBe(200)1878 expect(await res.text()).toBe('list books')1879 })18801881 it('Should return 200 response - GET /v2/book/123', async () => {1882 const res = await app.request('http://localhost/v2/book/123')1883 expect(res.status).toBe(200)1884 expect(await res.text()).toBe('book 123')1885 })1886 })18871888 describe('onError', () => {1889 const app = new Hono()1890 const sub = new Hono()18911892 app.use('*', async (c, next) => {1893 await next()1894 if (c.req.query('app-error')) {1895 throw new Error('This is Error')1896 }1897 })18981899 app.onError((err, c) => {1900 return c.text('onError by app', 500)1901 })19021903 sub.get('/posts/:id', async (c, next) => {1904 c.header('handler-chain', '1')1905 await next()1906 })19071908 sub.get('/posts/:id', (c) => {1909 return c.text(`post: ${c.req.param('id')}`)1910 })19111912 sub.get('/error', () => {1913 throw new Error('This is Error')1914 })19151916 sub.onError((err, c) => {1917 return c.text('onError by sub', 500)1918 })19191920 app.route('/sub', sub)19211922 it('GET /posts/123 for sub', async () => {1923 const res = await app.request('https://example.com/sub/posts/123')1924 expect(res.status).toBe(200)1925 expect(res.headers.get('handler-chain')).toBe('1')1926 expect(await res.text()).toBe('post: 123')1927 })19281929 it('should be handled by app', async () => {1930 const res = await app.request('https://example.com/sub/ok?app-error=1')1931 expect(res.status).toBe(500)1932 expect(await res.text()).toBe('onError by app')1933 })19341935 it('should be handled by sub', async () => {1936 const res = await app.request('https://example.com/sub/error')1937 expect(res.status).toBe(500)1938 expect(await res.text()).toBe('onError by sub')1939 })1940 })19411942 describe('onError for a single handler', () => {1943 const app = new Hono()1944 const sub = new Hono()19451946 sub.get('/ok', (c) => c.text('OK'))19471948 sub.get('/error', () => {1949 throw new Error('This is Error')1950 })19511952 sub.onError((err, c) => {1953 return c.text('onError by sub', 500)1954 })19551956 app.route('/sub', sub)19571958 it('ok', async () => {1959 const res = await app.request('https://example.com/sub/ok')1960 expect(res.status).toBe(200)1961 })19621963 it('error', async () => {1964 const res = await app.request('https://example.com/sub/error')1965 expect(res.status).toBe(500)1966 expect(await res.text()).toBe('onError by sub')1967 })1968 })19691970 describe('notFound', () => {1971 const app = new Hono()1972 const sub = new Hono()19731974 app.get('/explicit-404', async (c) => {1975 c.header('explicit', '1')1976 })19771978 app.notFound((c) => {1979 return c.text('404 Not Found by app', 404)1980 })19811982 sub.get('/ok', (c) => {1983 return c.text('ok')1984 })19851986 sub.get('/explicit-404', async (c) => {1987 c.header('explicit', '1')1988 })19891990 sub.notFound((c) => {1991 return c.text('404 Not Found by sub', 404)1992 })19931994 app.route('/sub', sub)19951996 it('/explicit-404 should be handled on app', async () => {1997 const res = await app.request('https://example.com/explicit-404')1998 expect(res.status).toBe(404)1999 expect(res.headers.get('explicit')).toBe('1')2000 expect(await res.text()).toBe('404 Not Found by app')The first 2,000 of 3,814 lines.