request.test.ts
This file
Path
src/request.test.ts
329 lines · 9.2 KiB · TypeScript
Last changed by
refactor(request): `toLowerCase()` is unnecessary for `req.header()` (#3880)Yusuke Wadabefore adoption65edaf2
History of this fileTake it
The walk stopped after 200 commits: lines older than 81a1f07 point at it.
fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 1–163why, one step back1import { HonoRequest } from './request'2import type { RouterRoute } from './types'34type RecursiveRecord<K extends string, T> = {5 [key in K]: T | RecursiveRecord<K, T>6}78describe('Query', () => {9 test('req.query() and req.queries()', () => {10 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')11 const req = new HonoRequest(rawRequest)1213 const page = req.query('page')14 expect(page).not.toBeUndefined()15 expect(page).toBe('2')1617 const q = req.query('q')18 expect(q).toBeUndefined()1920 const tags = req.queries('tag')21 expect(tags).not.toBeUndefined()22 expect(tags).toEqual(['A', 'B'])2324 const q2 = req.queries('q2')25 expect(q2).toBeUndefined()26 })2728 test('decode special chars', () => {29 const rawRequest = new Request('http://localhost?mail=framework%40hono.dev&tag=%401&tag=%402')30 const req = new HonoRequest(rawRequest)3132 const mail = req.query('mail')33 expect(mail).toBe('framework@hono.dev')3435 const tags = req.queries('tag')36 expect(tags).toEqual(['@1', '@2'])37 })38})3940describe('Param', () => {41 test('req.param() with ParamStash', () => {42 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')43 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [44 [45 [[undefined, {} as RouterRoute], { id: 0 }],46 [[undefined, {} as RouterRoute], { id: 0, name: 1 }],47 ],48 ['123', 'key'],49 ])5051 expect(req.param('id')).toBe('123')52 expect(req.param('name')).toBe(undefined)5354 req.routeIndex = 155 expect(req.param('id')).toBe('123')56 expect(req.param('name')).toBe('key')57 })5859 test('req.param() without ParamStash', () => {60 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')61 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [62 [63 [[undefined, {} as RouterRoute], { id: '123' }],64 [[undefined, {} as RouterRoute], { id: '456', name: 'key' }],65 ],66 ])6768 expect(req.param('id')).toBe('123')69 expect(req.param('name')).toBe(undefined)7071 req.routeIndex = 172 expect(req.param('id')).toBe('456')73 expect(req.param('name')).toBe('key')74 })75})7677describe('matchedRoutes', () => {78 test('req.routePath', () => {79 const handlerA = () => {}80 const handlerB = () => {}81 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')82 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [83 [84 [[handlerA, { handler: handlerA, method: 'GET', path: '/:id' }], { id: '123' }],85 [86 [handlerA, { handler: handlerB, method: 'GET', path: '/:id/:name' }],87 { id: '456', name: 'key' },88 ],89 ],90 ])9192 expect(req.matchedRoutes).toEqual([93 { handler: handlerA, method: 'GET', path: '/:id' },94 { handler: handlerB, method: 'GET', path: '/:id/:name' },95 ])96 })97})9899describe('routePath', () => {100 test('req.routePath', () => {101 const handlerA = () => {}102 const handlerB = () => {}103 const rawRequest = new Request('http://localhost?page=2&tag=A&tag=B')104 const req = new HonoRequest<'/:id/:name'>(rawRequest, '/123/key', [105 [106 [[handlerA, { handler: handlerA, method: 'GET', path: '/:id' }], { id: '123' }],107 [108 [handlerA, { handler: handlerB, method: 'GET', path: '/:id/:name' }],109 { id: '456', name: 'key' },110 ],111 ],112 ])113114 expect(req.routePath).toBe('/:id')115116 req.routeIndex = 1117 expect(req.routePath).toBe('/:id/:name')118 })119})120121describe('req.addValidatedData() and req.data()', () => {122 const rawRequest = new Request('http://localhost')123124 const payload = {125 title: 'hello',126 author: {127 name: 'young man',128 age: 20,129 },130 }131132 test('add data - json', () => {133 const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest)134 req.addValidatedData('json', payload)135 const data = req.valid('json')136 expect(data).toEqual(payload)137 })138139 test('replace data - json', () => {140 const req = new HonoRequest<'/', { json: typeof payload }>(rawRequest)141 req.addValidatedData('json', payload)142 req.addValidatedData('json', {143 tag: ['sport', 'music'],144 author: {145 tall: 170,146 },147 })148 const data = req.valid('json')149 expect(data).toEqual({150 author: {151 tall: 170,152 },153 tag: ['sport', 'music'],154 })155 })156})157158describe('headers', () => {159 test('empty string is a valid header value', () => {160 const req = new HonoRequest(new Request('http://localhost', { headers: { foo: '' } }))161 const foo = req.header('foo')162 expect(foo).toEqual('')163 })refactor(request): `toLowerCase()` is unnecessary for `req.header()` (#3880)Yusuke Wadabefore adoption65edaf2
lines 164–177why, one step back164165 test('Keys of the arguments for req.header() are not case-sensitive', () => {166 const req = new HonoRequest(167 new Request('http://localhost', {168 headers: {169 'Content-Type': 'application/json',170 apikey: 'abc',171 lowercase: 'lowercase value',172 },173 })174 )175 expect(req.header('Content-Type')).toBe('application/json')176 expect(req.header('ApiKey')).toBe('abc')177 })fix(validator): support multipart headers without a space separating boundary (#3286)Ernest Badubefore adoption81a1f07
lines 178–329why, one step back178})179180const text = '{"foo":"bar"}'181const json = { foo: 'bar' }182const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer183184describe('Body methods with caching', () => {185 test('req.text()', async () => {186 const req = new HonoRequest(187 new Request('http://localhost', {188 method: 'POST',189 body: text,190 })191 )192 expect(await req.text()).toEqual(text)193 expect(await req.json()).toEqual(json)194 expect(await req.arrayBuffer()).toEqual(buffer)195 expect(await req.blob()).toEqual(196 new Blob([text], {197 type: 'text/plain;charset=utf-8',198 })199 )200 })201202 test('req.json()', async () => {203 const req = new HonoRequest(204 new Request('http://localhost', {205 method: 'POST',206 body: '{"foo":"bar"}',207 })208 )209 expect(await req.json()).toEqual(json)210 expect(await req.text()).toEqual(text)211 expect(await req.arrayBuffer()).toEqual(buffer)212 expect(await req.blob()).toEqual(213 new Blob([text], {214 type: 'text/plain;charset=utf-8',215 })216 )217 })218219 test('req.arrayBuffer()', async () => {220 const buffer = new TextEncoder().encode('{"foo":"bar"}').buffer221 const req = new HonoRequest(222 new Request('http://localhost', {223 method: 'POST',224 body: buffer,225 })226 )227 expect(await req.arrayBuffer()).toEqual(buffer)228 expect(await req.text()).toEqual(text)229 expect(await req.json()).toEqual(json)230 expect(await req.blob()).toEqual(231 new Blob([text], {232 type: '',233 })234 )235 })236237 test('req.blob()', async () => {238 const blob = new Blob(['{"foo":"bar"}'], {239 type: 'application/json',240 })241 const req = new HonoRequest(242 new Request('http://localhost', {243 method: 'POST',244 body: blob,245 })246 )247 expect(await req.blob()).toEqual(blob)248 expect(await req.text()).toEqual(text)249 expect(await req.json()).toEqual(json)250 expect(await req.arrayBuffer()).toEqual(buffer)251 })252253 test('req.formData()', async () => {254 const data = new FormData()255 data.append('foo', 'bar')256 const req = new HonoRequest(257 new Request('http://localhost', {258 method: 'POST',259 body: data,260 })261 )262 expect((await req.formData()).get('foo')).toBe('bar')263 expect(async () => await req.text()).not.toThrow()264 expect(async () => await req.arrayBuffer()).not.toThrow()265 expect(async () => await req.blob()).not.toThrow()266 })267268 describe('req.parseBody()', async () => {269 it('should parse form data', async () => {270 const data = new FormData()271 data.append('foo', 'bar')272 const req = new HonoRequest(273 new Request('http://localhost', {274 method: 'POST',275 body: data,276 })277 )278 expect((await req.parseBody())['foo']).toBe('bar')279 expect(async () => await req.text()).not.toThrow()280 expect(async () => await req.arrayBuffer()).not.toThrow()281 expect(async () => await req.blob()).not.toThrow()282 })283284 describe('Return type', () => {285 let req: HonoRequest286 beforeEach(() => {287 const data = new FormData()288 data.append('foo', 'bar')289 req = new HonoRequest(290 new Request('http://localhost', {291 method: 'POST',292 body: data,293 })294 )295 })296297 it('without options', async () => {298 expectTypeOf((await req.parseBody())['key']).toEqualTypeOf<string | File>()299 })300301 it('{all: true}', async () => {302 expectTypeOf((await req.parseBody({ all: true }))['key']).toEqualTypeOf<303 string | File | (string | File)[]304 >()305 })306307 it('{dot: true}', async () => {308 expectTypeOf((await req.parseBody({ dot: true }))['key']).toEqualTypeOf<309 string | File | RecursiveRecord<string, string | File>310 >()311 })312313 it('{all: true, dot: true}', async () => {314 expectTypeOf((await req.parseBody({ all: true, dot: true }))['key']).toEqualTypeOf<315 | string316 | File317 | (string | File)[]318 | RecursiveRecord<string, string | File | (string | File)[]>319 >()320 })321322 it('specify return type explicitly', async () => {323 expectTypeOf(324 await req.parseBody<{ key1: string; key2: string }>({ all: true, dot: true })325 ).toEqualTypeOf<{ key1: string; key2: string }>()326 })327 })328 })329})