Skip to content
Myr

index.test.ts

This file

Path

src/helper/factory/index.test.ts

434 lines · 12.1 KiB · TypeScript

Last changed by

Not known.

History of this file

Take it

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

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 1–434why, one step back
1/* eslint-disable @typescript-eslint/no-unused-vars */
2import { expectTypeOf } from 'vitest'3import { hc } from '../../client'4import type { ClientRequest } from '../../client/types'5import { Hono } from '../../index'6import type { Env, ExtractSchema, H, MiddlewareHandler, ToSchema, TypedResponse } from '../../types'7import type { ContentfulStatusCode } from '../../utils/http-status'8import type { Equal, Expect } from '../../utils/types'9import { validator } from '../../validator'10import { createFactory, createMiddleware } from './index'1112describe('createMiddleware', () => {13 type Env = { Variables: { foo: string } }14 const app = new Hono()1516 const mw = (message: string) =>17 createMiddleware<Env>(async (c, next) => {18 expectTypeOf(c.var.foo).toEqualTypeOf<string>()19 c.set('foo', 'bar')20 await next()21 c.header('X-Message', message)22 })2324 const route = app.get('/message', mw('Hello Middleware'), (c) => {25 return c.text(`Hey, ${c.var.foo}`)26 })2728 it('Should return the correct header and the content', async () => {29 const res = await app.request('/message')30 expect(res.status).toBe(200)31 expect(res.headers.get('x-message')).toBe('Hello Middleware')32 expect(await res.text()).toBe('Hey, bar')33 })3435 it('Should provide the correct types', async () => {36 const client = hc<typeof route>('http://localhost')37 const url = client.message.$url()38 expect(url.pathname).toBe('/message')39 })4041 it('Should pass generics types to chained handlers', () => {42 type Bindings = {43 MY_VAR_IN_BINDINGS: string44 }4546 type Variables = {47 MY_VAR: string48 }4950 const app = new Hono<{ Bindings: Bindings }>()5152 app.get(53 '/',54 createMiddleware<{ Variables: Variables }>(async (c, next) => {55 await next()56 }),57 createMiddleware(async (c, next) => {58 await next()59 }),60 async (c) => {61 const v = c.get('MY_VAR')62 expectTypeOf(v).toEqualTypeOf<string>()63 }64 )65 })6667 it('Should default to MiddlewareHandler<E, P, I, Response>', async () => {68 const middleware = createMiddleware(async (c, next) => {69 await next()70 })71 type Expected = MiddlewareHandler<any, string, {}, Response>72 type _verify = Expect<Equal<Expected, typeof middleware>>73 })74})7576describe('createHandler', () => {77 const mw = (message: string) =>78 createMiddleware(async (c, next) => {79 await next()80 c.header('x-message', message)81 })8283 describe('Basic', () => {84 const factory = createFactory()85 const app = new Hono()8687 const handlersA = factory.createHandlers((c) => {88 return c.text('A')89 })90 const routesA = app.get('/a', ...handlersA)9192 const handlersB = factory.createHandlers(mw('B'), (c) => {93 return c.text('B')94 })95 app.get('/b', ...handlersB)9697 it('Should return 200 response - GET /a', async () => {98 const res = await app.request('/a')99 expect(res.status).toBe(200)100 expect(await res.text()).toBe('A')101 })102103 it('Should return 200 response with a custom header - GET /b', async () => {104 const res = await app.request('/b')105 expect(res.status).toBe(200)106 expect(res.headers.get('x-message')).toBe('B')107 expect(await res.text()).toBe('B')108 })109110 it('Should return correct path types - /a', () => {111 const client = hc<typeof routesA>('/')112 expectTypeOf(client).toEqualTypeOf<{113 a: ClientRequest<114 string,115 '/a',116 {117 $get: {118 input: {}119 output: 'A'120 outputFormat: 'text'121 status: ContentfulStatusCode122 }123 }124 >125 }>()126 })127 })128129 describe('Types', () => {130 type Env = { Variables: { foo: string } }131132 const factory = createFactory<Env>()133 const app = new Hono<Env>()134135 const handlers = factory.createHandlers(136 validator('query', () => {137 return {138 page: '1',139 }140 }),141 (c) => {142 const foo = c.var.foo143 const { page } = c.req.valid('query')144 return c.json({ page, foo })145 }146 )147 const routes = app.get('/posts', ...handlers)148149 type Expected = Hono<150 Env,151 ToSchema<152 'get',153 '/posts',154 {155 in: {156 query: {157 page: string158 }159 }160 },161 TypedResponse<{162 page: string163 foo: string164 }>165 >,166 '/'167 >168169 it('Should return correct types', () => {170 expectTypeOf(routes).toEqualTypeOf<Expected>()171 })172 })173174 // It's difficult to cover all possible patterns,175 // so these tests will only cover the minimal cases.176177 describe('Types - Complex', () => {178 type Env = { Variables: { foo: string } }179180 const factory = createFactory<Env>()181 const app = new Hono<Env>()182183 const handlers = factory.createHandlers(184 validator('header', () => {185 return {186 auth: 'token',187 }188 }),189 validator('query', () => {190 return {191 page: '1',192 }193 }),194 validator('json', () => {195 return {196 id: 123,197 }198 }),199 (c) => {200 const foo = c.var.foo201 const { auth } = c.req.valid('header')202 const { page } = c.req.valid('query')203 const { id } = c.req.valid('json')204 return c.json({ auth, page, foo, id })205 }206 )207 const routes = app.get('/posts', ...handlers)208209 type Expected = Hono<210 Env,211 ToSchema<212 'get',213 '/posts',214 {215 in: {216 header: {217 auth: string218 }219 } & {220 query: {221 page: string222 }223 } & {224 json: {225 id: number226 }227 }228 },229 TypedResponse<{230 auth: string231 page: string232 foo: string233 id: number234 }>235 >,236 '/'237 >238239 it('Should return correct types', () => {240 expectTypeOf(routes).toEqualTypeOf<Expected>()241 })242 })243244 describe('Types - Context Env with Multiple Middlewares', () => {245 const factory = createFactory()246247 const mw1 = createMiddleware<248 { Variables: { foo1: string } },249 string,250 { out: { query: { bar1: number } } }251 >(async () => {})252 const mw2 = createMiddleware<253 { Variables: { foo2: string } },254 string,255 { out: { query: { bar2: number } } }256 >(async () => {})257 const mw3 = createMiddleware<258 { Variables: { foo3: string } },259 string,260 { out: { query: { bar3: number } } }261 >(async () => {})262 const mw4 = createMiddleware<263 { Variables: { foo4: string } },264 string,265 { out: { query: { bar4: number } } }266 >(async () => {})267 const mw5 = createMiddleware<268 { Variables: { foo5: string } },269 string,270 { out: { query: { bar5: number } } }271 >(async () => {})272 const mw6 = createMiddleware<273 { Variables: { foo6: string } },274 string,275 { out: { query: { bar6: number } } }276 >(async () => {})277 const mw7 = createMiddleware<278 { Variables: { foo7: string } },279 string,280 { out: { query: { bar7: number } } }281 >(async () => {})282 const mw8 = createMiddleware<283 { Variables: { foo8: string } },284 string,285 { out: { query: { bar8: number } } }286 >(async () => {})287 const mw9 = createMiddleware<288 { Variables: { foo9: string } },289 string,290 { out: { query: { bar9: number } } }291 >(async () => {})292293 it('Should not throw type error', () => {294 factory.createHandlers(295 mw1,296 mw2,297 mw3,298 mw4,299 mw5,300 mw6,301 mw7,302 mw8,303 async (c) => {304 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()305 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()306 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()307 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()308 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()309 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()310 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()311 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()312 },313 (c) => c.json(0)314 )315316 factory.createHandlers(mw1, mw2, mw3, mw4, mw5, mw6, mw7, mw8, mw9, (c) => {317 expectTypeOf(c.var.foo1).toEqualTypeOf<string>()318 expectTypeOf(c.var.foo2).toEqualTypeOf<string>()319 expectTypeOf(c.var.foo3).toEqualTypeOf<string>()320 expectTypeOf(c.var.foo4).toEqualTypeOf<string>()321 expectTypeOf(c.var.foo5).toEqualTypeOf<string>()322 expectTypeOf(c.var.foo6).toEqualTypeOf<string>()323 expectTypeOf(c.var.foo7).toEqualTypeOf<string>()324 expectTypeOf(c.var.foo8).toEqualTypeOf<string>()325 expectTypeOf(c.var.foo9).toEqualTypeOf<string>()326327 return c.json({328 foo1: c.get('foo1'),329 foo2: c.get('foo2'),330 foo3: c.get('foo3'),331 foo4: c.get('foo4'),332 foo5: c.get('foo5'),333 foo6: c.get('foo6'),334 foo7: c.get('foo7'),335 foo8: c.get('foo8'),336 foo9: c.get('foo9'),337 })338 })339 })340 })341342 describe('Types - Multiple Handlers', () => {343 const factory = createFactory()344345 const [handler1, handler2] = factory.createHandlers(346 (c) => c.json({ first: 1 }),347 (c) => c.json({ second: 'second' as const })348 )349350 type ExtractOutput<R> = R extends H<any, any, any, TypedResponse<infer Inner>> ? Inner : never351352 type Handler1Output = ExtractOutput<typeof handler1>353 type Handler2Output = ExtractOutput<typeof handler2>354355 it('Should allow multiple handlers with independent return types', () => {356 expectTypeOf<Handler1Output>().toEqualTypeOf<{ first: number }>()357 expectTypeOf<Handler2Output>().toEqualTypeOf<{ second: 'second' }>()358 })359 })360})361362describe('createFactory', () => {363 describe('createApp', () => {364 type Env = { Variables: { foo: string } }365 const factory = createFactory<Env>({366 initApp: (app) => {367 app.use((c, next) => {368 c.set('foo', 'bar')369 return next()370 })371 },372 })373 const app = factory.createApp()374 it('Should set the correct type and initialize the app', async () => {375 app.get('/', (c) => {376 expectTypeOf(c.var.foo).toEqualTypeOf<string>()377 return c.text(c.var.foo)378 })379 const res = await app.request('/')380 expect(res.status).toBe(200)381 expect(await res.text()).toBe('bar')382 })383 })384385 describe('createMiddleware', () => {386 it('Should omit the `*` wildcard from the generated schema', () => {387 const factory = createFactory()388389 const middleware = factory.createMiddleware(async (_, next) => {390 await next()391 })392393 const routes = new Hono().use('*', middleware)394 type Actual = ExtractSchema<typeof routes>395 type Expected = {}396 type verify = Expect<Equal<Expected, Actual>>397 })398399 it('Should default to MiddlewareHandler<E, P, I, Response>', async () => {400 const factory = createFactory()401402 const middleware = factory.createMiddleware(async (c, next) => {403 await next()404 })405 type Expected = MiddlewareHandler<Env, string, {}, Response>406 type _verify = Expect<Equal<Expected, typeof middleware>>407 })408 })409410 it('Should use the default app options', async () => {411 const app = createFactory({ defaultAppOptions: { strict: false } }).createApp()412 app.get('/hello', (c) => c.text('hello'))413 const res = await app.request('/hello/')414 expect(res.status).toBe(200)415 expect(await res.text()).toBe('hello')416 })417418 it('Should override the default app options when creating', async () => {419 const app = createFactory({ defaultAppOptions: { strict: true } }).createApp({ strict: false })420 app.get('/hello', (c) => c.text('hello'))421 const res = await app.request('/hello/')422 expect(res.status).toBe(200)423 expect(await res.text()).toBe('hello')424 })425})426427describe('Lint rules', () => {428 it('Should not throw a eslint `unbound-method` error if destructed', () => {429 const { createApp, createHandlers, createMiddleware } = createFactory()430 expect(createApp).toBeDefined()431 expect(createHandlers).toBeDefined()432 expect(createMiddleware).toBeDefined()433 })434})