Skip to content
Myr

validator.test.ts

This file

Path

src/validator/validator.test.ts

743 lines 路 16.6 KiB 路 TypeScript

Last changed by

test(vitest): replace `jest` with `vitest` (#1404)Derrick Farrisbefore adoption5b07146

History of this file

Take it

1/* eslint-disable @typescript-eslint/no-unused-vars */2import type { ZodSchema } from 'zod'3import { z } from 'zod'4import { Hono } from '../hono'5import type { ExtractSchema, MiddlewareHandler, ValidationTargets } from '../types'6import type { Equal, Expect } from '../utils/types'7import type { ValidationFunction } from './validator'8import { validator } from './validator'910// Reference implementation for only testing11const zodValidator = <12  T extends ZodSchema,13  E extends {},14  P extends string,15  Target extends keyof ValidationTargets16>(17  target: Target,18  schema: T19): MiddlewareHandler<20  E,21  P,22  { in: { [K in Target]: z.input<T> }; out: { [K in Target]: z.output<T> } }23> =>24  validator(target, (value, c) => {25    const result = schema.safeParse(value)26    if (!result.success) {27      return c.text('Invalid!', 400)28    }29    const data = result.data as z.output<T>30    return data31  })3233describe('Validator middleware', () => {34  const app = new Hono()3536  const route = app.get(37    '/search',38    async (_c, next) => {39      await next()40    },41    validator('query', (value, c) => {42      type verify = Expect<Equal<Record<string, string | string[]>, typeof value>>43      if (!value) {44        return c.text('Invalid!', 400)45      }46    }),47    (c) => {48      return c.text('Valid!')49    }50  )5152  type Expected = {53    '/search': {54      $get: {55        input: {56          query: undefined57        }58        output: {}59      }60    }61  }6263  type Actual = ExtractSchema<typeof route>6465  type verify = Expect<Equal<Expected, Actual>>6667  it('Should return 200 response', async () => {68    const res = await app.request('http://localhost/search?q=foo')69    expect(res.status).toBe(200)70  })7172  it('Should return 400 response', async () => {73    const res = await app.request('http://localhost/search')74    expect(res.status).toBe(200)75  })76})7778describe('Malformed JSON', () => {79  const app = new Hono()8081  app.post(82    '/post',83    validator('json', (value, c) => {}),84    (c) => {85      return c.text('Valid!')86    }87  )8889  it('Should return 400 response', async () => {90    const res = await app.request('http://localhost/post', {91      method: 'POST',92    })93    expect(res.status).toBe(400)94  })95})9697describe('Validator middleware with a custom validation function', () => {98  const app = new Hono()99100  const validationFunction: ValidationFunction<{ id: string }, { id: number }> = (v) => {101    return {102      id: Number(v.id),103    }104  }105106  const route = app.post('/post', validator('json', validationFunction), (c) => {107    const post = c.req.valid('json')108    type Expected = {109      id: number110    }111    type verify = Expect<Equal<Expected, typeof post>>112    return c.jsonT({113      post,114    })115  })116117  type Expected = {118    '/post': {119      $post: {120        input: {121          json: {122            id: string123          }124        }125        output: {126          post: {127            id: number128          }129        }130      }131    }132  }133134  type Actual = ExtractSchema<typeof route>135  type verify2 = Expect<Equal<Expected, Actual>>136137  it('Should validate JSON with transformation and return 200 response', async () => {138    const res = await app.request('http://localhost/post', {139      method: 'POST',140      body: JSON.stringify({141        id: '123',142      }),143    })144    expect(res.status).toBe(200)145    expect(await res.json()).toEqual({146      post: {147        id: 123,148      },149    })150  })151})152153describe('Validator middleware with Zod validates JSON', () => {154  const app = new Hono()155156  const schema = z.object({157    id: z.number(),158    title: z.string(),159  })160161  const route = app.post('/post', zodValidator('json', schema), (c) => {162    const post = c.req.valid('json')163    type Expected = {164      id: number165      title: string166    }167    type verify = Expect<Equal<Expected, typeof post>>168    return c.jsonT({169      post: post,170    })171  })172173  type Expected = {174    '/post': {175      $post: {176        input: {177          json: {178            id: number179            title: string180          }181        }182        output: {183          post: {184            id: number185            title: string186          }187        }188      }189    }190  }191192  type Actual = ExtractSchema<typeof route>193194  type verify2 = Expect<Equal<Expected, Actual>>195196  it('Should validate JSON and return 200 response', async () => {197    const res = await app.request('http://localhost/post', {198      method: 'POST',199      body: JSON.stringify({200        id: 123,201        title: 'Hello',202      }),203    })204    expect(res.status).toBe(200)205    expect(await res.json()).toEqual({206      post: {207        id: 123,208        title: 'Hello',209      },210    })211  })212213  it('Should validate JSON and return 400 response', async () => {214    const res = await app.request('http://localhost/post', {215      method: 'POST',216      body: JSON.stringify({217        id: '123',218        title: 'Hello',219      }),220    })221    expect(res.status).toBe(400)222    expect(await res.text()).toBe('Invalid!')223  })224})225226describe('Validator middleware with Zod validates Form data', () => {227  const app = new Hono()228229  const schema = z.object({230    id: z.string(),231    title: z.string(),232  })233  app.post('/post', zodValidator('form', schema), (c) => {234    const post = c.req.valid('form')235    return c.jsonT({236      post: post,237    })238  })239240  it('Should validate Form data and return 200 response', async () => {241    const form = new FormData()242    form.append('id', '123')243    form.append('title', 'Hello')244    const res = await app.request('http://localhost/post', {245      method: 'POST',246      body: form,247    })248    expect(res.status).toBe(200)249    expect(await res.json()).toEqual({250      post: {251        id: '123',252        title: 'Hello',253      },254    })255  })256257  it('Should validate Form data and return 400 response', async () => {258    const res = await app.request('http://localhost/post', {259      method: 'POST',260    })261    expect(res.status).toBe(400)262    expect(await res.text()).toBe('Invalid!')263  })264})265266describe('Validator middleware with Zod validates query params', () => {267  const app = new Hono()268269  const schema = z.object({270    page: z271      .string()272      .refine((v) => {273        return !isNaN(Number(v))274      })275      .transform((v) => {276        return Number(v)277      }),278    tag: z.array(z.string()),279  })280281  app.get('/search', zodValidator('query', schema), (c) => {282    const res = c.req.valid('query')283    return c.jsonT({284      page: res.page,285      tags: res.tag,286    })287  })288289  it('Should validate query params and return 200 response', async () => {290    const res = await app.request('http://localhost/search?page=123&tag=a&tag=b')291    expect(res.status).toBe(200)292    expect(await res.json()).toEqual({293      page: 123,294      tags: ['a', 'b'],295    })296  })297298  it('Should validate query params and return 400 response', async () => {299    const res = await app.request('http://localhost/search?page=onetwothree')300    expect(res.status).toBe(400)301    expect(await res.text()).toBe('Invalid!')302  })303})304305describe('Validator middleware with Zod validates queries params - with `queries` will be obsolete in v4', () => {306  const app = new Hono()307308  const schema = z.object({309    tags: z.array(z.string()),310  })311312  app.get('/posts', zodValidator('queries', schema), (c) => {313    const res = c.req.valid('queries')314    return c.jsonT({315      tags: res.tags,316    })317  })318319  it('Should validate queries params and return 200 response', async () => {320    const res = await app.request('http://localhost/posts?tags=book&tags=movie')321    expect(res.status).toBe(200)322    expect(await res.json()).toEqual({323      tags: ['book', 'movie'],324    })325  })326327  it('Should validate queries params and return 400 response', async () => {328    const res = await app.request('http://localhost/posts')329    expect(res.status).toBe(400)330    expect(await res.text()).toBe('Invalid!')331  })332})333334describe('Validator middleware with Zod validates param', () => {335  const app = new Hono()336337  const schema = z.object({338    id: z339      .string()340      .regex(/^[0-9]+$/)341      .transform((v) => {342        return Number(v)343      }),344    title: z.string(),345  })346  app.get('/users/:id/books/:title', zodValidator('param', schema), (c) => {347    const param = c.req.valid('param')348    return c.jsonT({349      param: param,350    })351  })352353  it('Should validate Form data and return 200 response', async () => {354    const res = await app.request('http://localhost/users/123/books/Hello')355    expect(res.status).toBe(200)356    expect(await res.json()).toEqual({357      param: {358        id: 123,359        title: 'Hello',360      },361    })362  })363364  it('Should validate Form data and return 400 response', async () => {365    const res = await app.request('http://localhost/users/0.123/books/Hello')366    expect(res.status).toBe(400)367    expect(await res.text()).toBe('Invalid!')368  })369})370371describe('Validator middleware with Zod validates header values', () => {372  const app = new Hono()373374  const schema = z.object({375    'x-request-id': z.string().uuid(),376  })377378  app.get('/ping', zodValidator('header', schema), (c) => {379    const data = c.req.valid('header')380    const xRequestId = data['x-request-id']381    return c.jsonT({382      xRequestId,383    })384  })385386  it('Should validate header values and return 200 response', async () => {387    const res = await app.request('/ping', {388      headers: {389        'x-request-id': '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',390      },391    })392    expect(res.status).toBe(200)393    expect(await res.json()).toEqual({394      xRequestId: '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',395    })396  })397398  it('Should validate header values and return 400 response', async () => {399    const res = await app.request('http://localhost/ping', {400      headers: {401        'x-request-id': 'invalid-key',402      },403    })404    expect(res.status).toBe(400)405    expect(await res.text()).toBe('Invalid!')406  })407})408409describe('Validator middleware with Zod validates cookies', () => {410  const app = new Hono()411412  const schema = z.object({413    debug: z.enum(['0', '1']),414  })415416  app.get('/api/user', zodValidator('cookie', schema), (c) => {417    const { debug } = c.req.valid('cookie')418    return c.jsonT({419      debug,420    })421  })422423  it('Should validate cookies and return 200 response', async () => {424    const res = await app.request('/api/user', {425      headers: {426        Cookie: 'debug=0',427      },428    })429    expect(res.status).toBe(200)430    expect(await res.json()).toEqual({431      debug: '0',432    })433  })434435  it('Should validate cookies and return 400 response', async () => {436    const res = await app.request('/api/user', {437      headers: {438        Cookie: 'debug=true',439      },440    })441    expect(res.status).toBe(400)442    expect(await res.text()).toBe('Invalid!')443  })444})445446describe('Validator middleware with Zod multiple validators', () => {447  const app = new Hono<{ Variables: { id: number } }>()448  const route = app.post(449    '/posts',450    zodValidator(451      'query',452      z.object({453        page: z454          .string()455          .refine((v) => {456            return !isNaN(Number(v))457          })458          .transform((v) => {459            return Number(v)460          }),461      })462    ),463    zodValidator(464      'form',465      z.object({466        title: z.string(),467      })468    ),469    (c) => {470      const id = c.get('id')471      type verify = Expect<Equal<number, typeof id>>472      const formValidatedData = c.req.valid('form')473      type verify2 = Expect<Equal<{ title: string }, typeof formValidatedData>>474      const { page } = c.req.valid('query')475      const { title } = c.req.valid('form')476      return c.jsonT({ page, title })477    }478  )479480  type Actual = ExtractSchema<typeof route>481482  type Expected = {483    '/posts': {484      $post: {485        input: {486          query: {487            page: string488          }489        } & {490          form: {491            title: string492          }493        }494        output: {495          page: number496          title: string497        }498      }499    }500  }501502  type verify = Expect<Equal<Expected, Actual>>503504  it('Should validate both query param and form data and return 200 response', async () => {505    const form = new FormData()506    form.append('title', 'Hello')507    const res = await app.request('http://localhost/posts?page=2', {508      method: 'POST',509      body: form,510    })511    expect(res.status).toBe(200)512    expect(await res.json()).toEqual({513      page: 2,514      title: 'Hello',515    })516  })517518  it('Should validate both query param and form data and return 400 response', async () => {519    const res = await app.request('http://localhost/posts?page=2', {520      method: 'POST',521    })522    expect(res.status).toBe(400)523    expect(await res.text()).toBe('Invalid!')524  })525})526527it('With path parameters', () => {528  const app = new Hono()529530  const route = app.put(531    '/posts/:id',532    validator('form', () => {533      return {534        title: 'Foo',535      }536    }),537    (c) => {538      return c.text('Valid!')539    }540  )541542  type Expected = {543    '/posts/:id': {544      $put: {545        input: {546          form: {547            title: string548          }549        } & {550          param: {551            id: string552          }553        }554        output: {}555      }556    }557  }558559  type Actual = ExtractSchema<typeof route>560  type verify = Expect<Equal<Expected, Actual>>561})562563it('`on`', () => {564  const app = new Hono()565566  const route = app.on(567    'PURGE',568    '/purge',569    validator('form', () => {570      return {571        tag: 'foo',572      }573    }),574    validator('query', () => {575      return {576        q: 'bar',577      }578    }),579    (c) => {580      return c.jsonT({581        success: true,582      })583    }584  )585586  type Expected = {587    '/purge': {588      $purge: {589        input: {590          form: {591            tag: string592          }593        } & {594          query: {595            q: string596          }597        }598        output: {599          success: boolean600        }601      }602    }603  }604605  type Actual = ExtractSchema<typeof route>606  type verify = Expect<Equal<Expected, Actual>>607})608609it('`app.on`', () => {610  const app = new Hono()611612  const route = app613    .get(614      '/posts',615      validator('query', () => {616        return {617          page: '2',618        }619      }),620      (c) => {621        return c.jsonT({622          posts: [623            {624              title: 'foo',625            },626          ],627        })628      }629    )630    .post(631      validator('json', () => {632        return {633          title: 'Hello',634        }635      }),636      validator('query', () => {637        return {638          title: 'Hello',639        }640      }),641      (c) => {642        return c.jsonT({643          success: true,644        })645      }646    )647648  type Actual = ExtractSchema<typeof route>649  //type verify = Expect<Equal<Expected, Actual>>650})651652describe('Clone Request object', () => {653  describe('json', () => {654    const app = new Hono()655    app.post(656      '/',657      validator('json', () => {658        return {659          foo: 'bar',660        }661      }),662      async (c) => {663        // `c.req.json()` should not throw the error664        await c.req.json()665        // `c.req.text()` should not throw the error666        await c.req.text()667        // `c.req.arrayBuffer()` should not throw the error668        await c.req.arrayBuffer()669        // `c.req.blob()` should not throw the error670        await c.req.blob()671        return c.text('foo')672      }673    )674675    it('Should not throw the error with c.req.json()', async () => {676      const req = new Request('http://localhost', {677        method: 'POST',678        body: JSON.stringify({ foo: 'bar' }),679      })680      const res = await app.request(req)681      expect(res.status).toBe(200)682    })683  })684685  describe('form', () => {686    const app = new Hono()687    app.post(688      '/',689      validator('form', () => {690        return {691          foo: 'bar',692        }693      }),694      async (c) => {695        // `c.req.parseBody()` should not throw the error696        await c.req.parseBody()697        // `c.req.text()` should not throw the error698        await c.req.text()699        // `c.req.arrayBuffer()` should not throw the error700        await c.req.arrayBuffer()701        // `c.req.blob()` should not throw the error702        await c.req.blob()703        return c.text('foo')704      }705    )706707    it('Should not throw the error with c.req.parseBody()', async () => {708      const body = new FormData()709      body.append('foo', 'bar')710      const req = new Request('http://localhost', {711        method: 'POST',712        body: body,713      })714      const res = await app.request(req)715      expect(res.status).toBe(200)716    })717  })718})719720describe('Async validator function', () => {721  const app = new Hono()722723  app.get(724    '/posts',725    validator('query', async () => {726      return {727        page: '1',728      }729    }),730    (c) => {731      const { page } = c.req.valid('query')732      return c.json({ page })733    }734  )735736  it('Should get the values from the async function', async () => {737    const res = await app.request('/posts')738    expect(res.status).toBe(200)739    expect(await res.json()).toEqual({740      page: '1',741    })742  })743})