Skip to content
Myr

request.test.ts

This file

Path

src/request.test.ts

504 lines 路 15.2 KiB 路 TypeScript

Last changed by

Merge pull request #4461 from honojs/nextYusuke Wadabefore adoptionf0c0377

History of this file

Take it

1import { HTTPException } from './http-exception'2import { cloneRawRequest, HonoRequest } from './request'3import type { RouterRoute } from './types'45type RecursiveRecord<K extends string, T> = {6  [key in K]: T | RecursiveRecord<K, T>7}89describe('Query', () => {10  test('req.query() and req.queries()', () => {11    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')12    const req = new HonoRequest(rawRequest)1314    const page = req.query('page')15    expect(page).not.toBeUndefined()16    expect(page).toBe('2')1718    const q = req.query('q')19    expect(q).toBeUndefined()2021    const tags = req.queries('tag')22    expect(tags).not.toBeUndefined()23    expect(tags).toEqual(['A', 'B'])2425    const q2 = req.queries('q2')26    expect(q2).toBeUndefined()27  })2829  test('decode special chars', () => {30    const rawRequest = new Request('http://localhost?mail=framework%40hono.dev&tag=%401&tag=%402')31    const req = new HonoRequest(rawRequest)3233    const mail = req.query('mail')34    expect(mail).toBe('framework@hono.dev')3536    const tags = req.queries('tag')37    expect(tags).toEqual(['@1', '@2'])38  })39})4041describe('Param', () => {42  test('req.param() should return empty string for zero-length match', () => {43    // Simulate a route like '/:remaining{.*}' matching '/'44    const rawRequest = new Request('http://localhost/')45    const req = new HonoRequest<'/:remaining{.*}'>(rawRequest, '/', [46      [[[undefined, {} as RouterRoute], { remaining: 0 }]],47      [''], // ParamStash with empty string for remaining48    ])4950    // Single param access should be empty string, not undefined51    expect(req.param('remaining')).toBe('')5253    // All params should include key with empty string value54    const all = req.param()55    expect(all).toEqual({ remaining: '' })56  })57  test('req.param() with ParamStash', () => {58    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')59    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [60      [61        [[undefined, {} as RouterRoute], { id: 0 }],62        [[undefined, {} as RouterRoute], { id: 0, name: 1 }],63      ],64      ['123', 'key'],65    ])6667    expect(req.param('id')).toBe('123')68    expect(req.param('name')).toBe(undefined)6970    req.routeIndex = 171    expect(req.param('id')).toBe('123')72    expect(req.param('name')).toBe('key')73  })7475  test('req.param() without ParamStash', () => {76    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')77    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [78      [79        [[undefined, {} as RouterRoute], { id: '123' }],80        [[undefined, {} as RouterRoute], { id: '456', name: 'key' }],81      ],82    ])8384    expect(req.param('id')).toBe('123')85    expect(req.param('name')).toBe(undefined)8687    req.routeIndex = 188    expect(req.param('id')).toBe('456')89    expect(req.param('name')).toBe('key')90  })9192  test('req.param() returns empty string for missing param', () => {93    const rawRequest = new Request('http://localhost')94    const req = new HonoRequest<'/:remaining'>(rawRequest, '/', [95      [[[undefined, {} as RouterRoute], { remaining: 0 }]],96      [''],97    ])98    expect(req.param('remaining')).toBe('')99  })100101  test('req.param() without argument returns object with empty string for missing param', () => {102    const rawRequest = new Request('http://localhost')103    const req = new HonoRequest<'/:remaining'>(rawRequest, '/', [104      [[[undefined, {} as RouterRoute], { remaining: 0 }]],105      [''],106    ])107    expect(req.param()).toEqual({ remaining: '' })108  })109})110111describe('matchedRoutes', () => {112  test('req.routePath', () => {113    const handlerA = () => {}114    const handlerB = () => {}115    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')116    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [117      [118        [119          [handlerA, { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' }],120          { id: '123' },121        ],122        [123          [handlerA, { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' }],124          { id: '456', name: 'key' },125        ],126      ],127    ])128129    expect(req.matchedRoutes).toEqual([130      { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' },131      { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' },132    ])133  })134})135136describe('routePath', () => {137  test('req.routePath', () => {138    const handlerA = () => {}139    const handlerB = () => {}140    const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')141    const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [142      [143        [144          [handlerA, { basePath: '/', handler: handlerA, method: 'GET', path: '/:id' }],145          { id: '123' },146        ],147        [148          [handlerA, { basePath: '/', handler: handlerB, method: 'GET', path: '/:id/:name' }],149          { id: '456', name: 'key' },150        ],151      ],152    ])153154    expect(req.routePath).toBe('/:id')155156    req.routeIndex = 1157    expect(req.routePath).toBe('/:id/:name')158  })159})160161describe('req.addValidatedData() and req.data()', () => {162  const rawRequest = new Request('http://localhost')163164  const payload = {165    title: 'hello',166    author: {167      name: 'young man',168      age: 20,169    },170  }171172  test('add data - json', () => {173    const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest)174    req.addValidatedData('json', payload)175    const data = req.valid('json')176    expect(data).toEqual(payload)177  })178179  test('replace data - json', () => {180    const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest)181    req.addValidatedData('json', payload)182    req.addValidatedData('json', {183      tag: ['sport', 'music'],184      author: {185        tall: 170,186      },187    })188    const data = req.valid('json')189    expect(data).toEqual({190      author: {191        tall: 170,192      },193      tag: ['sport', 'music'],194    })195  })196})197198describe('headers', () => {199  test('empty string is a valid header value', () => {200    const req = new HonoRequest(new Request('http://localhost', { headers: { foo: '' } }))201    const foo = req.header('foo')202    expect(foo).toEqual('')203  })204205  test('Keys of the arguments for req.header() are not case-sensitive', () => {206    const req = new HonoRequest(207      new Request('http://localhost', {208        headers: {209          'Content-Type': 'application/json',210          apikey: 'abc',211          lowercase: 'lowercase value',212        },213      })214    )215    expect(req.header('Content-Type')).toBe('application/json')216    expect(req.header('ApiKey')).toBe('abc')217  })218})219220const text = '{"foo":"bar"}'221const json = { foo: 'bar' }222const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer223224describe('Body methods with caching', () => {225  test('req.text()', async () => {226    const req = new HonoRequest(227      new Request('http://localhost', {228        method: 'POST',229        body: text,230      })231    )232    expect(await req.text()).toEqual(text)233    expect(await req.json()).toEqual(json)234    expect(await req.arrayBuffer()).toEqual(buffer)235    expect(await req.blob()).toEqual(236      new Blob([text], {237        type: 'text/plain;charset=utf-8',238      })239    )240  })241242  test('req.json()', async () => {243    const req = new HonoRequest(244      new Request('http://localhost', {245        method: 'POST',246        body: '{"foo":"bar"}',247      })248    )249    expect(await req.json()).toEqual(json)250    expect(await req.text()).toEqual(text)251    expect(await req.arrayBuffer()).toEqual(buffer)252    expect(await req.blob()).toEqual(253      new Blob([text], {254        type: 'text/plain;charset=utf-8',255      })256    )257  })258259  test('req.json() should keep the content as is', async () => {260    const text = '{ "foo" : "bar" }'261    const req = new HonoRequest(262      new Request('http://localhost', {263        method: 'POST',264        body: text,265      })266    )267    expect(await req.json()).toEqual(JSON.parse(text))268    expect(await req.text()).toEqual(text)269  })270271  test('req.arrayBuffer()', async () => {272    const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer273    const req = new HonoRequest(274      new Request('http://localhost', {275        method: 'POST',276        body: buffer,277      })278    )279    expect(await req.arrayBuffer()).toEqual(buffer)280    expect(await req.text()).toEqual(text)281    expect(await req.json()).toEqual(json)282    expect(await req.blob()).toEqual(283      new Blob([text], {284        type: '',285      })286    )287  })288289  test('req.blob()', async () => {290    const blob = new Blob(['{"foo":"bar"}'], {291      type: 'application/json',292    })293    const req = new HonoRequest(294      new Request('http://localhost', {295        method: 'POST',296        body: blob,297      })298    )299    expect(await req.blob()).toEqual(blob)300    expect(await req.text()).toEqual(text)301    expect(await req.json()).toEqual(json)302    expect(await req.arrayBuffer()).toEqual(buffer)303  })304305  test('req.formData()', async () => {306    const data = new FormData()307    data.append('foo', 'bar')308    const req = new HonoRequest(309      new Request('http://localhost', {310        method: 'POST',311        body: data,312      })313    )314    expect((await req.formData()).get('foo')).toBe('bar')315    expect(async () => await req.text()).not.toThrow()316    expect(async () => await req.arrayBuffer()).not.toThrow()317    expect(async () => await req.blob()).not.toThrow()318  })319320  describe('req.parseBody()', async () => {321    it('should parse form data', async () => {322      const data = new FormData()323      data.append('foo', 'bar')324      const req = new HonoRequest(325        new Request('http://localhost', {326          method: 'POST',327          body: data,328        })329      )330      expect((await req.parseBody())['foo']).toBe('bar')331      expect(async () => await req.text()).not.toThrow()332      expect(async () => await req.arrayBuffer()).not.toThrow()333      expect(async () => await req.blob()).not.toThrow()334    })335336    describe('Return type', () => {337      let req: HonoRequest338      beforeEach(() => {339        const data = new FormData()340        data.append('foo', 'bar')341        req = new HonoRequest(342          new Request('http://localhost', {343            method: 'POST',344            body: data,345          })346        )347      })348349      it('without options', async () => {350        expectTypeOf((await req.parseBody())['key']).toEqualTypeOf<string | File>()351      })352353      it('{all: true}', async () => {354        expectTypeOf((await req.parseBody({ all: true }))['key']).toEqualTypeOf<355          string | File | (string | File)[]356        >()357      })358359      it('{dot: true}', async () => {360        expectTypeOf((await req.parseBody({ dot: true }))['key']).toEqualTypeOf<361          string | File | RecursiveRecord<string, string | File>362        >()363      })364365      it('{all: true, dot: true}', async () => {366        expectTypeOf((await req.parseBody({ all: true, dot: true }))['key']).toEqualTypeOf<367          | string368          | File369          | (string | File)[]370          | RecursiveRecord<string, string | File | (string | File)[]>371        >()372      })373374      it('specify return type explicitly', async () => {375        expectTypeOf(376          await req.parseBody<{ key1: string; key2: string }>({ all: true, dot: true })377        ).toEqualTypeOf<{ key1: string; key2: string }>()378      })379    })380  })381})382383describe('cloneRawRequest', () => {384  test('clones unconsumed request object', async () => {385    const req = new HonoRequest(386      new Request('http://localhost', {387        method: 'POST',388        headers: {389          'Content-Type': 'application/json',390          'X-Custom-Header': 'custom-value',391        },392        body: text,393        cache: 'no-cache',394        credentials: 'include',395        integrity: 'sha256-test',396        mode: 'cors',397        redirect: 'follow',398        referrer: 'http://example.com',399        referrerPolicy: 'origin',400      })401    )402403    const clonedReq = await cloneRawRequest(req)404405    expect(clonedReq.method).toBe('POST')406    expect(clonedReq.url).toBe('http://localhost/')407    expect(await clonedReq.text()).toBe(text)408    expect(clonedReq.headers.get('Content-Type')).toBe('application/json')409    expect(clonedReq.headers.get('X-Custom-Header')).toBe('custom-value')410    expect(clonedReq.cache).toBe('no-cache')411    expect(clonedReq.credentials).toBe('include')412    expect(clonedReq.integrity).toBe('sha256-test')413    expect(clonedReq.mode).toBe('cors')414    expect(clonedReq.redirect).toBe('follow')415    expect(clonedReq.referrer).toBe('http://example.com/')416    expect(clonedReq.referrerPolicy).toBe('origin')417    expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)418    expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)419  })420421  test('clones consumed request object', async () => {422    const req = new HonoRequest(423      new Request('http://localhost', {424        method: 'POST',425        headers: {426          Authorization: 'Bearer token123',427        },428        body: text,429        mode: 'same-origin',430        credentials: 'same-origin',431      })432    )433    await req.json()434435    const clonedReq = await cloneRawRequest(req)436437    expect(clonedReq.method).toBe('POST')438    expect(clonedReq.url).toBe('http://localhost/')439    expect(await clonedReq.json()).toEqual(json)440    expect(clonedReq.headers.get('Authorization')).toBe('Bearer token123')441    expect(clonedReq.mode).toBe('same-origin')442    expect(clonedReq.credentials).toBe('same-origin')443    expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)444    expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)445  })446447  test('clones GET request without body', async () => {448    const req = new HonoRequest(449      new Request('http://localhost', {450        method: 'GET',451        headers: {452          'User-Agent': 'test-agent',453        },454        cache: 'default',455        redirect: 'manual',456        referrerPolicy: 'no-referrer',457      })458    )459460    const clonedReq = await cloneRawRequest(req)461462    expect(clonedReq.method).toBe('GET')463    expect(clonedReq.url).toBe('http://localhost/')464    expect(clonedReq.headers.get('User-Agent')).toBe('test-agent')465    expect(clonedReq.cache).toBe('default')466    expect(clonedReq.redirect).toBe('manual')467    expect(clonedReq.referrerPolicy).toBe('no-referrer')468    expect(req.raw, 'cloned request should be a different object reference').not.toBe(clonedReq)469    expect(req.raw, 'cloned request should contain the same properties').toMatchObject(clonedReq)470  })471472  test('clones request when raw body was consumed directly without HonoRequest methods', async () => {473    const req = new HonoRequest(474      new Request('http://localhost', {475        method: 'POST',476        headers: {477          'Content-Type': 'application/json',478        },479        body: text,480      })481    )482483    // Consume the raw request body directly, bypassing HonoRequest methods484    // This means bodyCache will be empty485    await req.raw.text()486487    expect(req.raw.bodyUsed).toBe(true)488    expect(Object.keys(req.bodyCache).length).toBe(0)489490    let error: HTTPException | undefined = undefined491    try {492      await cloneRawRequest(req)493    } catch (e) {494      expect(e).toBeInstanceOf(HTTPException)495      error = e as HTTPException496    }497498    expect(error).not.toBeUndefined()499    expect((error as HTTPException).status).toBe(500)500    expect((error as HTTPException).message).toContain(501      'Cannot clone request: body was already consumed and not cached'502    )503  })504})