validator.test.ts
This file
Path
src/validator/validator.test.ts
1,209 lines 路 28.5 KiB 路 TypeScript
Last changed by
fix(validator): Fixed a bug in hono/validator where URL Encoded Data could not be validated if the Content-Type included charset. (#3297)uttkbefore adoptionc378dd9
History of this fileTake it
1/* eslint-disable @typescript-eslint/no-unused-vars */2import type { ZodSchema } from 'zod'3import { z } from 'zod'4import { Hono } from '../hono'5import { HTTPException } from '../http-exception'6import type {7 ErrorHandler,8 ExtractSchema,9 MiddlewareHandler,10 ParsedFormValue,11 ValidationTargets,12} from '../types'13import type { StatusCode } from '../utils/http-status'14import type { Equal, Expect } from '../utils/types'15import type { ValidationFunction } from './validator'16import { validator } from './validator'1718// Reference implementation for only testing19const zodValidator = <20 T extends ZodSchema,21 E extends {},22 P extends string,23 Target extends keyof ValidationTargets24>(25 target: Target,26 schema: T27): MiddlewareHandler<28 E,29 P,30 { in: { [K in Target]: z.input<T> }; out: { [K in Target]: z.output<T> } }31> =>32 validator(target, (value, c) => {33 const result = schema.safeParse(value)34 if (!result.success) {35 return c.text('Invalid!', 400)36 }37 const data = result.data as z.output<T>38 return data39 })4041describe('Basic', () => {42 const app = new Hono()4344 const route = app.get(45 '/search',46 async (_c, next) => {47 await next()48 },49 validator('query', (value, c) => {50 type verify = Expect<Equal<Record<string, string | string[]>, typeof value>>51 if (!value) {52 return c.text('Invalid!', 400)53 }54 }),55 (c) => {56 return c.text('Valid!')57 }58 )5960 type Expected = {61 '/search': {62 $get: {63 input: {64 query: undefined65 }66 output: 'Valid!'67 outputFormat: 'text'68 status: StatusCode69 }70 }71 }7273 type Actual = ExtractSchema<typeof route>7475 type verify = Expect<Equal<Expected, Actual>>7677 it('Should return 200 response', async () => {78 const res = await app.request('http://localhost/search?q=foo')79 expect(res.status).toBe(200)80 })8182 it('Should return 400 response', async () => {83 const res = await app.request('http://localhost/search')84 expect(res.status).toBe(200)85 })86})8788const onErrorHandler: ErrorHandler = (e, c) => {89 if (e instanceof HTTPException) {90 return c.json({ message: e.message, success: false }, e.status)91 }92 return c.json({ message: e.message }, 500)93}9495describe('JSON', () => {96 const app = new Hono()97 app.post(98 '/post',99 validator('json', (value) => value),100 (c) => {101 return c.json(c.req.valid('json'))102 }103 )104105 it('Should return 200 response with a valid JSON data', async () => {106 const res = await app.request('http://localhost/post', {107 method: 'POST',108 body: JSON.stringify({ foo: 'bar' }),109 headers: {110 'Content-Type': 'application/json',111 },112 })113 expect(res.status).toBe(200)114 const data = await res.json()115 expect(data).toEqual({ foo: 'bar' })116 })117118 it('Should not validate if Content-Type is not set', async () => {119 const res = await app.request('http://localhost/post', {120 method: 'POST',121 body: JSON.stringify({ foo: 'bar' }),122 })123 expect(res.status).toBe(200)124 const data = await res.json()125 expect(data.foo).toBeUndefined()126 })127128 it('Should not validate if Content-Type is wrong', async () => {129 const res = await app.request('http://localhost/post', {130 method: 'POST',131 headers: {132 'Content-Type': 'text/plain;charset=utf-8',133 },134 body: JSON.stringify({ foo: 'bar' }),135 })136 expect(res.status).toBe(200)137 })138139 it('Should validate if Content-Type is a application/json with a charset', async () => {140 const res = await app.request('http://localhost/post', {141 method: 'POST',142 headers: {143 'Content-Type': 'application/json; charset=utf8',144 },145 body: JSON.stringify({ foo: 'bar' }),146 })147 expect(res.status).toBe(200)148 expect(await res.json()).toEqual({ foo: 'bar' })149 })150151 it('Should validate if Content-Type is a subtype like application/merge-patch+json', async () => {152 const res = await app.request('http://localhost/post', {153 method: 'POST',154 headers: {155 'Content-Type': 'application/merge-patch+json',156 },157 body: JSON.stringify({ foo: 'bar' }),158 })159 expect(res.status).toBe(200)160 expect(await res.json()).toEqual({ foo: 'bar' })161 })162163 it('Should validate if Content-Type is application/vnd.api+json', async () => {164 const res = await app.request('http://localhost/post', {165 method: 'POST',166 headers: {167 'Content-Type': 'application/vnd.api+json',168 },169 body: JSON.stringify({ foo: 'bar' }),170 })171 expect(res.status).toBe(200)172 expect(await res.json()).toEqual({ foo: 'bar' })173 })174175 it('Should not validate if Content-Type does not start with application/json', async () => {176 const res = await app.request('http://localhost/post', {177 method: 'POST',178 headers: {179 'Content-Type': 'Xapplication/json',180 },181 body: JSON.stringify({ foo: 'bar' }),182 })183 expect(res.status).toBe(200)184 const data = await res.json()185 expect(data.foo).toBeUndefined()186 })187})188189describe('Malformed JSON', () => {190 const app = new Hono()191 app.post(192 '/post',193 validator('json', (value) => value),194 (c) => {195 return c.json(c.req.valid('json'))196 }197 )198199 it('Should return 400 response if the body data is not a valid JSON', async () => {200 const formData = new FormData()201 formData.append('foo', 'bar')202 const res = await app.request('http://localhost/post', {203 method: 'POST',204 headers: {205 'Content-Type': 'application/json',206 },207 body: formData,208 })209 expect(res.status).toBe(400)210 })211})212213describe('FormData', () => {214 const app = new Hono()215 app.post(216 '/post',217 validator('form', (value) => value),218 (c) => {219 return c.json(c.req.valid('form'))220 }221 )222223 it('Should return 200 response with a valid form data', async () => {224 const formData = new FormData()225 formData.append('message', 'hi')226 const res = await app.request('http://localhost/post', {227 method: 'POST',228 body: formData,229 })230 expect(res.status).toBe(200)231 expect(await res.json()).toEqual({ message: 'hi' })232 })233234 it('Should validate a URL Encoded Data', async () => {235 const params = new URLSearchParams()236 params.append('foo', 'bar')237 const res = await app.request('/post', {238 method: 'POST',239 body: params,240 headers: {241 'content-type': 'application/x-www-form-urlencoded',242 },243 })244 expect(res.status).toBe(200)245 expect(await res.json()).toEqual({246 foo: 'bar',247 })248 })249250 it('Should validate if Content-Type is a application/x-www-form-urlencoded with a charset', async () => {251 const params = new URLSearchParams()252 params.append('foo', 'bar')253 const res = await app.request('/post', {254 method: 'POST',255 body: params,256 headers: {257 'content-type': 'application/x-www-form-urlencoded; charset=UTF-8',258 },259 })260 expect(res.status).toBe(200)261 expect(await res.json()).toEqual({262 foo: 'bar',263 })264 })265266 it('Should return `foo[]` as an array', async () => {267 const form = new FormData()268 form.append('foo[]', 'bar1')269 form.append('foo[]', 'bar2')270 const res = await app.request('/post', {271 method: 'POST',272 body: form,273 })274 expect(res.status).toBe(200)275 expect(await res.json()).toEqual({276 'foo[]': ['bar1', 'bar2'],277 })278 })279280 it('Should return `foo` as an array if multiple values are appended', async () => {281 const form = new FormData()282 form.append('foo', 'bar1')283 form.append('foo', 'bar2')284 form.append('foo', 'bar3')285 const res = await app.request('/post', {286 method: 'POST',287 body: form,288 })289 expect(res.status).toBe(200)290 expect(await res.json()).toEqual({291 foo: ['bar1', 'bar2', 'bar3'],292 })293 })294})295296describe('Malformed FormData request', () => {297 const app = new Hono()298 app.post(299 '/post',300 validator('form', (value) => value),301 (c) => {302 return c.json(c.req.valid('form'))303 }304 )305 app.onError(onErrorHandler)306307 it('Should return 400 response, for malformed content type header', async () => {308 const res = await app.request('http://localhost/post', {309 method: 'POST',310 body: 'hi',311 headers: {312 'content-type': 'multipart/form-data',313 },314 })315 expect(res.status).toBe(400)316 const data = await res.json()317 expect(data['success']).toBe(false)318 expect(data['message']).toMatch(/^Malformed FormData request./)319 })320})321322describe('JSON and FormData', () => {323 const app = new Hono()324 app.post(325 '/',326 validator('json', (value) => value),327 validator('form', (value) => value),328 async (c) => {329 const jsonData = c.req.valid('json')330 const formData = c.req.valid('form')331 return c.json({332 json: jsonData,333 form: formData,334 })335 }336 )337338 it('Should validate a JSON request', async () => {339 const res = await app.request('/', {340 method: 'POST',341 body: JSON.stringify({ foo: 'bar' }),342 headers: {343 'Content-Type': 'application/json',344 },345 })346 expect(res.status).toBe(200)347 const data = await res.json()348 expect(data.json).toEqual({ foo: 'bar' })349 })350351 it('Should validate a FormData request', async () => {352 const form = new FormData()353 form.append('foo', 'bar')354 const res = await app.request('/', {355 method: 'POST',356 body: form,357 })358 expect(res.status).toBe(200)359 const data = await res.json()360 expect(data.form).toEqual({ foo: 'bar' })361 })362})363364describe('Cached contents', () => {365 describe('json', () => {366 const app = new Hono()367 const bodyTypes = ['json', 'text', 'arrayBuffer', 'blob']368369 for (const type of bodyTypes) {370 app.post(371 `/${type}`,372 async (c, next) => {373 // @ts-expect-error not type safe374 await c.req[type]()375 await next()376 },377 validator('json', (value) => {378 if (value instanceof Promise) {379 throw new Error('Value is Promise')380 }381 return value382 }),383 async (c) => {384 const data = await c.req.json()385 return c.json(data, 200)386 }387 )388 }389390 for (const type of bodyTypes) {391 const endpoint = `/${type}`392 it(`Should return the cached JSON content - ${endpoint}`, async () => {393 const res = await app.request(endpoint, {394 method: 'POST',395 body: JSON.stringify({ message: 'Hello' }),396 headers: {397 'Content-Type': 'application/json',398 },399 })400 expect(res.status).toBe(200)401 expect(await res.json()).toEqual({ message: 'Hello' })402 })403 }404 })405406 describe('Cached content', () => {407 const app = new Hono()408 const bodyTypes = ['formData', 'text', 'arrayBuffer', 'blob']409410 for (const type of bodyTypes) {411 app.post(412 `/${type}`,413 async (c, next) => {414 // @ts-expect-error not type safe415 await c.req[type]()416 await next()417 },418 validator('form', (value) => {419 if (value instanceof Promise) {420 throw new Error('Value is Promise')421 }422 return value423 }),424 async (c) => {425 return c.json({ message: 'OK' }, 200)426 }427 )428 }429430 for (const type of bodyTypes) {431 const endpoint = `/${type}`432 it(`Should return the cached FormData content - ${endpoint}`, async () => {433 const form = new FormData()434 form.append('message', 'Hello')435 const res = await app.request(endpoint, {436 method: 'POST',437 body: form,438 })439 expect(res.status).toBe(200)440 expect(await res.json()).toEqual({ message: 'OK' })441 })442 }443 })444})445446describe('Validator middleware with a custom validation function', () => {447 const app = new Hono()448449 const validationFunction: ValidationFunction<{ id: string }, { id: number }> = (v) => {450 return {451 id: Number(v.id),452 }453 }454455 const route = app.post('/post', validator('json', validationFunction), (c) => {456 const post = c.req.valid('json')457 type Expected = {458 id: number459 }460 type verify = Expect<Equal<Expected, typeof post>>461 return c.json({462 post,463 })464 })465466 type Expected = {467 '/post': {468 $post: {469 input: {470 json: {471 id: string472 }473 }474 output: {475 post: {476 id: number477 }478 }479 outputFormat: 'json'480 status: StatusCode481 }482 }483 }484485 type Actual = ExtractSchema<typeof route>486 type verify2 = Expect<Equal<Expected, Actual>>487488 it('Should validate JSON with transformation and return 200 response', async () => {489 const res = await app.request('http://localhost/post', {490 method: 'POST',491 headers: {492 'Content-Type': 'application/json',493 },494 body: JSON.stringify({495 id: '123',496 }),497 })498 expect(res.status).toBe(200)499 expect(await res.json()).toEqual({500 post: {501 id: 123,502 },503 })504 })505})506507describe('Validator middleware with Zod validates JSON', () => {508 const app = new Hono()509510 const schema = z.object({511 id: z.number(),512 title: z.string(),513 })514515 const route = app.post('/post', zodValidator('json', schema), (c) => {516 const post = c.req.valid('json')517 type Expected = {518 id: number519 title: string520 }521 type verify = Expect<Equal<Expected, typeof post>>522 return c.json({523 post: post,524 })525 })526527 type Expected = {528 '/post': {529 $post: {530 input: {531 json: {532 id: number533 title: string534 }535 }536 output: {537 post: {538 id: number539 title: string540 }541 }542 outputFormat: 'json'543 status: StatusCode544 }545 }546 }547548 type Actual = ExtractSchema<typeof route>549550 type verify2 = Expect<Equal<Expected, Actual>>551552 it('Should validate JSON and return 200 response', async () => {553 const res = await app.request('http://localhost/post', {554 method: 'POST',555 headers: {556 'Content-Type': 'application/json',557 },558 body: JSON.stringify({559 id: 123,560 title: 'Hello',561 }),562 })563 expect(res.status).toBe(200)564 expect(await res.json()).toEqual({565 post: {566 id: 123,567 title: 'Hello',568 },569 })570 })571572 it('Should validate JSON and return 400 response', async () => {573 const res = await app.request('http://localhost/post', {574 method: 'POST',575 headers: {576 'Content-Type': 'application/json',577 },578 body: JSON.stringify({579 id: '123',580 title: 'Hello',581 }),582 })583 expect(res.status).toBe(400)584 expect(await res.text()).toBe('Invalid!')585 })586})587588describe('Validator middleware with Zod validates Form data', () => {589 const app = new Hono()590591 const schema = z.object({592 id: z.string(),593 title: z.string(),594 })595 app.post('/post', zodValidator('form', schema), (c) => {596 const post = c.req.valid('form')597 return c.json({598 post: post,599 })600 })601602 it('Should validate Form data and return 200 response', async () => {603 const form = new FormData()604 form.append('id', '123')605 form.append('title', 'Hello')606 const res = await app.request('http://localhost/post', {607 method: 'POST',608 body: form,609 })610 expect(res.status).toBe(200)611 expect(await res.json()).toEqual({612 post: {613 id: '123',614 title: 'Hello',615 },616 })617 })618619 it('Should validate Form data and return 400 response', async () => {620 const res = await app.request('http://localhost/post', {621 method: 'POST',622 })623 expect(res.status).toBe(400)624 expect(await res.text()).toBe('Invalid!')625 })626})627628describe('Validator middleware with Zod validates query params', () => {629 const app = new Hono()630631 const schema = z.object({632 page: z633 .string()634 .refine((v) => {635 return !isNaN(Number(v))636 })637 .transform((v) => {638 return Number(v)639 }),640 tag: z.array(z.string()),641 })642643 app.get('/search', zodValidator('query', schema), (c) => {644 const res = c.req.valid('query')645 return c.json({646 page: res.page,647 tags: res.tag,648 })649 })650651 it('Should validate query params and return 200 response', async () => {652 const res = await app.request('http://localhost/search?page=123&tag=a&tag=b')653 expect(res.status).toBe(200)654 expect(await res.json()).toEqual({655 page: 123,656 tags: ['a', 'b'],657 })658 })659660 it('Should validate query params and return 400 response', async () => {661 const res = await app.request('http://localhost/search?page=onetwothree')662 expect(res.status).toBe(400)663 expect(await res.text()).toBe('Invalid!')664 })665})666667describe('Validator middleware with Zod validates param', () => {668 const app = new Hono()669670 const schema = z.object({671 id: z672 .string()673 .regex(/^[0-9]+$/)674 .transform((v) => {675 return Number(v)676 }),677 title: z.string(),678 })679 app.get('/users/:id/books/:title', zodValidator('param', schema), (c) => {680 const param = c.req.valid('param')681 return c.json({682 param: param,683 })684 })685686 it('Should validate Form data and return 200 response', async () => {687 const res = await app.request('http://localhost/users/123/books/Hello')688 expect(res.status).toBe(200)689 expect(await res.json()).toEqual({690 param: {691 id: 123,692 title: 'Hello',693 },694 })695 })696697 it('Should validate Form data and return 400 response', async () => {698 const res = await app.request('http://localhost/users/0.123/books/Hello')699 expect(res.status).toBe(400)700 expect(await res.text()).toBe('Invalid!')701 })702})703704describe('Validator middleware with Zod validates header values', () => {705 const app = new Hono()706707 const schema = z.object({708 'x-request-id': z.string().uuid(),709 })710711 app.get('/ping', zodValidator('header', schema), (c) => {712 const data = c.req.valid('header')713 const xRequestId = data['x-request-id']714 return c.json({715 xRequestId,716 })717 })718719 it('Should validate header values and return 200 response', async () => {720 const res = await app.request('/ping', {721 headers: {722 'x-request-id': '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',723 },724 })725 expect(res.status).toBe(200)726 expect(await res.json()).toEqual({727 xRequestId: '6ec0bd7f-11c0-43da-975e-2a8ad9ebae0b',728 })729 })730731 it('Should validate header values and return 400 response', async () => {732 const res = await app.request('http://localhost/ping', {733 headers: {734 'x-request-id': 'invalid-key',735 },736 })737 expect(res.status).toBe(400)738 expect(await res.text()).toBe('Invalid!')739 })740})741742describe('Validator middleware with Zod validates cookies', () => {743 const app = new Hono()744745 const schema = z.object({746 debug: z.enum(['0', '1']),747 })748749 app.get('/api/user', zodValidator('cookie', schema), (c) => {750 const { debug } = c.req.valid('cookie')751 return c.json({752 debug,753 })754 })755756 it('Should validate cookies and return 200 response', async () => {757 const res = await app.request('/api/user', {758 headers: {759 Cookie: 'debug=0',760 },761 })762 expect(res.status).toBe(200)763 expect(await res.json()).toEqual({764 debug: '0',765 })766 })767768 it('Should validate cookies and return 400 response', async () => {769 const res = await app.request('/api/user', {770 headers: {771 Cookie: 'debug=true',772 },773 })774 expect(res.status).toBe(400)775 expect(await res.text()).toBe('Invalid!')776 })777})778779describe('Validator middleware with Zod multiple validators', () => {780 const app = new Hono<{ Variables: { id: number } }>()781 const route = app.post(782 '/posts',783 zodValidator(784 'query',785 z.object({786 page: z787 .string()788 .refine((v) => {789 return !isNaN(Number(v))790 })791 .transform((v) => {792 return Number(v)793 }),794 })795 ),796 zodValidator(797 'form',798 z.object({799 title: z.string(),800 })801 ),802 (c) => {803 const id = c.get('id')804 type verify = Expect<Equal<number, typeof id>>805 const formValidatedData = c.req.valid('form')806 type verify2 = Expect<Equal<{ title: string }, typeof formValidatedData>>807 const { page } = c.req.valid('query')808 const { title } = c.req.valid('form')809 return c.json({ page, title })810 }811 )812813 type Actual = ExtractSchema<typeof route>814815 type Expected = {816 '/posts': {817 $post: {818 input: {819 query: {820 page: string821 }822 } & {823 form: {824 title: string825 }826 }827 output: {828 page: number829 title: string830 }831 outputFormat: 'json'832 status: StatusCode833 }834 }835 }836837 type verify = Expect<Equal<Expected, Actual>>838839 it('Should validate both query param and form data and return 200 response', async () => {840 const form = new FormData()841 form.append('title', 'Hello')842 const res = await app.request('http://localhost/posts?page=2', {843 method: 'POST',844 body: form,845 })846 expect(res.status).toBe(200)847 expect(await res.json()).toEqual({848 page: 2,849 title: 'Hello',850 })851 })852853 it('Should validate both query param and form data and return 400 response', async () => {854 const res = await app.request('http://localhost/posts?page=2', {855 method: 'POST',856 })857 expect(res.status).toBe(400)858 expect(await res.text()).toBe('Invalid!')859 })860})861862it('With path parameters', () => {863 const app = new Hono()864865 const route = app.put(866 '/posts/:id',867 validator('param', () => {868 return {869 id: '123',870 }871 }),872 validator('form', () => {873 return {874 title: 'Foo',875 }876 }),877 (c) => {878 return c.text('Valid!')879 }880 )881882 type Expected = {883 '/posts/:id': {884 $put: {885 input: {886 form: {887 title: ParsedFormValue | ParsedFormValue[]888 }889 } & {890 param: {891 id: string892 }893 }894 output: 'Valid!'895 outputFormat: 'text'896 status: StatusCode897 }898 }899 }900901 type Actual = ExtractSchema<typeof route>902 type verify = Expect<Equal<Expected, Actual>>903})904905it('`on`', () => {906 const app = new Hono()907908 const route = app.on(909 'PURGE',910 '/purge',911 validator('form', () => {912 return {913 tag: 'foo',914 }915 }),916 validator('query', () => {917 return {918 q: 'bar',919 }920 }),921 (c) => {922 return c.json({923 success: true,924 })925 }926 )927928 type Expected = {929 '/purge': {930 $purge: {931 input: {932 form: {933 tag: ParsedFormValue | ParsedFormValue[]934 }935 } & {936 query: {937 q: string | string[]938 }939 }940 output: {941 success: boolean942 }943 outputFormat: 'json'944 status: StatusCode945 }946 }947 }948949 type Actual = ExtractSchema<typeof route>950 type verify = Expect<Equal<Expected, Actual>>951})952953it('`app.on`', () => {954 const app = new Hono()955956 const route = app957 .get(958 '/posts',959 validator('query', () => {960 return {961 page: '2',962 }963 }),964 (c) => {965 return c.json({966 posts: [967 {968 title: 'foo',969 },970 ],971 })972 }973 )974 .post(975 validator('json', () => {976 return {977 title: 'Hello',978 }979 }),980 validator('query', () => {981 return {982 title: 'Hello',983 }984 }),985 (c) => {986 return c.json({987 success: true,988 })989 }990 )991992 type Actual = ExtractSchema<typeof route>993 //type verify = Expect<Equal<Expected, Actual>>994})995996describe('Clone Request object', () => {997 describe('json', () => {998 const app = new Hono()999 app.post(1000 '/',1001 validator('json', () => {1002 return {1003 foo: 'bar',1004 }1005 }),1006 async (c) => {1007 // `c.req.json()` should not throw the error1008 await c.req.json()1009 // `c.req.text()` should not throw the error1010 await c.req.text()1011 // `c.req.arrayBuffer()` should not throw the error1012 await c.req.arrayBuffer()1013 // `c.req.blob()` should not throw the error1014 await c.req.blob()1015 return c.text('foo')1016 }1017 )10181019 it('Should not throw the error with c.req.json()', async () => {1020 const req = new Request('http://localhost', {1021 method: 'POST',1022 headers: {1023 'Content-Type': 'application/json',1024 },1025 body: JSON.stringify({ foo: 'bar' }),1026 })1027 const res = await app.request(req)1028 expect(res.status).toBe(200)1029 })1030 })10311032 describe('form', () => {1033 const app = new Hono()1034 app.post(1035 '/',1036 validator('form', () => {1037 return {1038 foo: 'bar',1039 }1040 }),1041 async (c) => {1042 // `c.req.parseBody()` should not throw the error1043 await c.req.parseBody()1044 // `c.req.text()` should not throw the error1045 await c.req.text()1046 // `c.req.arrayBuffer()` should not throw the error1047 await c.req.arrayBuffer()1048 // `c.req.blob()` should not throw the error1049 await c.req.blob()1050 return c.text('foo')1051 }1052 )10531054 app.post(1055 '/cached',1056 async (c, next) => {1057 await c.req.parseBody()1058 await next()1059 },1060 validator('form', (value) => {1061 if (value instanceof FormData) {1062 throw new Error('The value should not be a FormData')1063 }1064 return value1065 }),1066 (c) => {1067 const v = c.req.valid('form')1068 return c.json(v)1069 }1070 )10711072 it('Should not throw the error with c.req.parseBody()', async () => {1073 const body = new FormData()1074 body.append('foo', 'bar')1075 const req = new Request('http://localhost', {1076 method: 'POST',1077 body: body,1078 })1079 const res = await app.request(req)1080 expect(res.status).toBe(200)1081 })10821083 it('Should not be an instance of FormData if the formData is cached', async () => {1084 const body = new FormData()1085 body.append('foo', 'bar')1086 const req = new Request('http://localhost/cached', {1087 method: 'POST',1088 body: body,1089 })1090 const res = await app.request(req)1091 expect(res.status).toBe(200)1092 expect(await res.json()).toEqual({ foo: 'bar' })1093 })1094 })1095})10961097describe('Async validator function', () => {1098 const app = new Hono()10991100 app.get(1101 '/posts',1102 validator('query', async () => {1103 return {1104 page: '1',1105 }1106 }),1107 (c) => {1108 const { page } = c.req.valid('query')1109 return c.json({ page })1110 }1111 )11121113 it('Should get the values from the async function', async () => {1114 const res = await app.request('/posts')1115 expect(res.status).toBe(200)1116 expect(await res.json()).toEqual({1117 page: '1',1118 })1119 })1120})11211122describe('Validator with using Zod directly', () => {1123 it('Should exclude Response & TypedResponse type', () => {1124 const testSchema = z.object({1125 name: z.string(),1126 age: z.number(),1127 type: z.enum(['a']),1128 })1129 const app = new Hono()11301131 const route = app.post(1132 '/posts',1133 validator('json', (value, c) => {1134 const parsed = testSchema.safeParse(value)1135 if (!parsed.success) {1136 return c.json({ foo: 'bar' }, 401)1137 }1138 return parsed.data1139 }),1140 (c) => {1141 const data = c.req.valid('json')1142 expectTypeOf(data.name).toEqualTypeOf<string>()1143 return c.json(1144 {1145 message: 'Created!',1146 },1147 2011148 )1149 }1150 )11511152 expectTypeOf<ExtractSchema<typeof route>>().toEqualTypeOf<{1153 '/posts': {1154 $post: {1155 input: {1156 json: {1157 type: 'a'1158 name: string1159 age: number1160 }1161 }1162 output: {1163 message: string1164 }1165 outputFormat: 'json'1166 status: 2011167 }1168 }1169 }>()1170 })1171})11721173describe('Transform', () => {1174 it('Should be number when the type is transformed', () => {1175 const route = new Hono().get(1176 '/',1177 validator('query', async () => {1178 return {1179 page: 1,1180 }1181 }),1182 (c) => {1183 const { page } = c.req.valid('query')1184 expectTypeOf(page).toEqualTypeOf<number>()1185 return c.json({ page })1186 }1187 )11881189 type Expected = {1190 '/': {1191 $get: {1192 input: {1193 query: {1194 page: string | string[]1195 }1196 }1197 output: {1198 page: number1199 }1200 outputFormat: 'json'1201 status: StatusCode1202 }1203 }1204 }12051206 type Actual = ExtractSchema<typeof route>1207 type verify = Expect<Equal<Expected, Actual>>1208 })1209})