Skip to content
Myr

utils.test.ts

This file

Path

src/client/utils.test.ts

358 lines · 12.2 KiB · TypeScript

Last changed by

chore(eslint): upgrade `@hono/eslint-config` (#4781)Jonathan Hainesbefore adoption5d59ac7

History of this file

Take it

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

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 1–5why, one step back
1import { HttpResponse, http } from 'msw'
2import { setupServer } from 'msw/node'3import { Hono } from '../hono'4import type { Expect, Equal } from '../utils/types'5import { hc } from './client'

chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626

lines 6–8why, one step back
6import {
7 buildSearchParams,8 deepMerge,

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

line 9why, one step back
9 parseResponse,

chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626

lines 10–124why, one step back
10 mergePath,
11 removeIndexString,12 replaceUrlParam,13 replaceUrlProtocol,14} from './utils'1516describe('mergePath', () => {17 it('Should merge paths correctly', () => {18 expect(mergePath('http://localhost', '/api')).toBe('http://localhost/api')19 expect(mergePath('http://localhost/', '/api')).toBe('http://localhost/api')20 expect(mergePath('http://localhost', 'api')).toBe('http://localhost/api')21 expect(mergePath('http://localhost/', 'api')).toBe('http://localhost/api')22 expect(mergePath('http://localhost/', '/')).toBe('http://localhost/')23 })24})2526describe('replaceUrlParams', () => {27 it('Should replace correctly', () => {28 const url = 'http://localhost/posts/:postId/comments/:commentId'29 const params = {30 postId: '123',31 commentId: '456',32 }33 const replacedUrl = replaceUrlParam(url, params)34 expect(replacedUrl).toBe('http://localhost/posts/123/comments/456')35 })3637 it('Should replace correctly when there is regex pattern', () => {38 const url = 'http://localhost/posts/:postId{[abc]+}/comments/:commentId{[0-9]+}'39 const params = {40 postId: 'abc',41 commentId: '456',42 }43 const replacedUrl = replaceUrlParam(url, params)44 expect(replacedUrl).toBe('http://localhost/posts/abc/comments/456')45 })4647 it('Should replace correctly when there is regex pattern with length limit', () => {48 const url = 'http://localhost/year/:year{[1-9]{1}[0-9]{3}}/month/:month{[0-9]{2}}'49 const params = {50 year: '2024',51 month: '2',52 }53 const replacedUrl = replaceUrlParam(url, params)54 expect(replacedUrl).toBe('http://localhost/year/2024/month/2')55 })5657 it('Should replace correctly when it has optional parameters', () => {58 const url = 'http://localhost/something/:firstId/:secondId/:version?'59 const params = {60 firstId: '123',61 secondId: '456',62 version: undefined,63 }64 const replacedUrl = replaceUrlParam(url, params)65 expect(replacedUrl).toBe('http://localhost/something/123/456')66 })67})6869describe('buildSearchParams', () => {70 it('Should build URLSearchParams correctly', () => {71 const query = {72 id: '123',73 type: 'test',74 tag: ['a', 'b'],75 }76 const searchParams = buildSearchParams(query)77 expect(searchParams.toString()).toBe('id=123&type=test&tag=a&tag=b')78 })79})8081describe('replaceUrlProtocol', () => {82 it('Should replace http to ws', () => {83 const url = 'http://localhost'84 const newUrl = replaceUrlProtocol(url, 'ws')85 expect(newUrl).toBe('ws://localhost')86 })8788 it('Should replace https to wss', () => {89 const url = 'https://localhost'90 const newUrl = replaceUrlProtocol(url, 'ws')91 expect(newUrl).toBe('wss://localhost')92 })9394 it('Should replace ws to http', () => {95 const url = 'ws://localhost'96 const newUrl = replaceUrlProtocol(url, 'http')97 expect(newUrl).toBe('http://localhost')98 })99100 it('Should replace wss to https', () => {101 const url = 'wss://localhost'102 const newUrl = replaceUrlProtocol(url, 'http')103 expect(newUrl).toBe('https://localhost')104 })105})106107describe('removeIndexString', () => {108 it('Should remove last `/index` string', () => {109 let url = 'http://localhost/index'110 let newUrl = removeIndexString(url)111 expect(newUrl).toBe('http://localhost/')112113 url = '/index'114 newUrl = removeIndexString(url)115 expect(newUrl).toBe('')116117 url = '/sub/index'118 newUrl = removeIndexString(url)119 expect(newUrl).toBe('/sub')120121 url = '/subindex'122 newUrl = removeIndexString(url)123 expect(newUrl).toBe('/subindex')124 })

fix(client): handle query parameters in `removeIndexString` (#4352)Yusuke Wadabefore adoption6b19b5e

lines 125–142why, one step back
125
126 it('Should remove `/index` with query parameters', () => {127 let url = 'http://localhost/index?page=123&limit=20'128 let newUrl = removeIndexString(url)129 expect(newUrl).toBe('http://localhost/?page=123&limit=20')130131 url = 'https://example.com/index?q=search'132 newUrl = removeIndexString(url)133 expect(newUrl).toBe('https://example.com/?q=search')134135 url = '/api/index?filter=test'136 newUrl = removeIndexString(url)137 expect(newUrl).toBe('/api?filter=test')138139 url = '/index?a=1&b=2&c=3'140 newUrl = removeIndexString(url)141 expect(newUrl).toBe('?a=1&b=2&c=3')142 })

chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626

lines 143–164why, one step back
143})
144145describe('deepMerge', () => {146 it('should return the source object if the target object is not an object', () => {147 const target = null148 const source = 'not an object' as unknown as Record<string, unknown>149 const result = deepMerge(target, source)150 expect(result).toEqual(source)151 })152153 it('should merge two objects with object properties', () => {154 expect(155 deepMerge(156 { headers: { hono: '1' }, timeout: 2, params: {} },157 { headers: { hono: '2', demo: 2 }, params: undefined }158 )159 ).toStrictEqual({160 params: undefined,161 headers: { hono: '2', demo: 2 },162 timeout: 2,163 })164 })

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 165–167why, one step back
165})
166167describe('parseResponse', async () => {

chore(eslint): upgrade `@hono/eslint-config` (#4781)Jonathan Hainesbefore adoption5d59ac7

line 168why, one step back
168 const _app = new Hono()

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 169–170why, one step back
169 .get('/text', (c) => c.text('hi'))
170 .get('/json', (c) => c.json({ message: 'hi' }))

fix(parseResponse): should not include error responses in result (#4348)Trung Dangbefore adoption08a80e2

lines 171–184why, one step back
171 .get('/might-error-json', (c) => {
172 if (Math.random() > 0.5) {173 return c.json({ error: 'error' }, 500)174 }175 return c.json({ data: [{ id: 1 }, { id: 2 }] })176 })177 .get('/might-error-mixed-json-text', (c) => {178 if (Math.random() > 0.5) {179 return c.text('500 Internal Server Error', 500)180 }181 return c.json({ message: 'Success' })182 })183 .get('/200-explicit', (c) => c.text('OK', 200))184 .get('/404', (c) => c.text('404 Not Found', 404))

feat(parseResponse): set `DetailedError.name` (+ error tests) (#4344)Trung Dangbefore adoption855e5b1

line 185why, one step back
185 .get('/500', (c) => c.text('500 Internal Server Error', 500))

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 186–198why, one step back
186 .get('/raw', (c) => {
187 c.header('content-type', '')188 return c.body('hello')189 })190 .get('/rawUnknown', (c) => {191 c.header('content-type', 'x/custom-type')192 return c.body('hello')193 })194 .get('/rawBuffer', (c) => {195 c.header('content-type', 'x/custom-type')196 return c.body(new TextEncoder().encode('hono'))197 })198

chore(eslint): upgrade `@hono/eslint-config` (#4781)Jonathan Hainesbefore adoption5d59ac7

line 199why, one step back
199 const client = hc<typeof _app>('http://localhost')

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 200–207why, one step back
200
201 const server = setupServer(202 http.get('http://localhost/text', () => {203 return HttpResponse.text('hi')204 }),205 http.get('http://localhost/json', () => {206 return HttpResponse.json({ message: 'hi' })207 }),

fix(parseResponse): should not include error responses in result (#4348)Trung Dangbefore adoption08a80e2

lines 208–222why, one step back
208 http.get('http://localhost/might-error-json', () => {
209 if (Math.random() > 0.5) {210 return HttpResponse.json({ error: 'error' }, { status: 500 })211 }212 return HttpResponse.json({ data: [{ id: 1 }, { id: 2 }] })213 }),214 http.get('http://localhost/might-error-mixed-json-text', () => {215 if (Math.random() > 0.5) {216 return HttpResponse.text('500 Internal Server Error', { status: 500 })217 }218 return HttpResponse.json({ message: 'Success' })219 }),220 http.get('http://localhost/200-explicit', () => {221 return HttpResponse.text('OK', { status: 200 })222 }),

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 223–225why, one step back
223 http.get('http://localhost/404', () => {
224 return HttpResponse.text('404 Not Found', { status: 404 })225 }),

feat(parseResponse): set `DetailedError.name` (+ error tests) (#4344)Trung Dangbefore adoption855e5b1

lines 226–228why, one step back
226 http.get('http://localhost/500', () => {
227 return HttpResponse.text('500 Internal Server Error', { status: 500 })228 }),

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 229–243why, one step back
229 http.get('http://localhost/raw', () => {
230 return HttpResponse.text('hello', {231 headers: {232 'content-type': '',233 },234 })235 }),236 http.get('http://localhost/rawUnknown', () => {237 return HttpResponse.text('hello', {238 headers: {239 'content-type': 'x/custom-type',240 },241 })242 }),243 http.get('http://localhost/rawBuffer', () => {

fix(parseResponse): should not include error responses in result (#4348)Trung Dangbefore adoption08a80e2

line 244why, one step back
244 return HttpResponse.arrayBuffer(new TextEncoder().encode('hono').buffer, {

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 245–266why, one step back
245 headers: {
246 'content-type': 'x/custom-type',247 },248 })249 })250 )251252 beforeAll(() => server.listen())253 afterEach(() => server.resetHandlers())254 afterAll(() => server.close())255256 await Promise.all([257 it('should auto parse the text response - async fetch', async () => {258 const result = await parseResponse(client.text.$get())259 expect(result).toBe('hi')260 type _verify = Expect<Equal<typeof result, 'hi'>>261 }),262 it('should auto parse the text response - sync fetch', async () => {263 const result = await parseResponse(await client.text.$get())264 expect(result).toBe('hi')265 type _verify = Expect<Equal<typeof result, 'hi'>>266 }),

fix(parseResponse): should not include error responses in result (#4348)Trung Dangbefore adoption08a80e2

lines 267–271why, one step back
267 it('should auto parse text response - explicit 200', async () => {
268 const result = await parseResponse(client['200-explicit'].$get())269 expect(result).toBe('OK')270 type _verify = Expect<Equal<typeof result, 'OK'>>271 }),

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 272–293why, one step back
272 it('should auto parse the json response - async fetch', async () => {
273 const result = await parseResponse(client.json.$get())274 expect(result).toEqual({ message: 'hi' })275 type _verify = Expect<Equal<typeof result, { message: string }>>276 }),277 it('should auto parse the json response - sync fetch', async () => {278 const result = await parseResponse(await client.json.$get())279 expect(result).toEqual({ message: 'hi' })280 type _verify = Expect<Equal<typeof result, { message: string }>>281 }),282 it('should throw error when the response is not ok', async () => {283 await expect(parseResponse(client['404'].$get())).rejects.toThrowError('404 Not Found')284 }),285 it('should parse as text for raw responses without content-type header', async () => {286 const result = await parseResponse(client.raw.$get())287 expect(result).toBe('hello')288 type _verify = Expect<Equal<typeof result, 'hello'>>289 }),290 it('should parse as unknown string for raw buffer responses with unknown content-type header', async () => {291 const result = await parseResponse(client.rawBuffer.$get())292 expect(result).toMatchInlineSnapshot('"hono"')293 type _verify = Expect<Equal<typeof result, string>>

feat(parseResponse): set `DetailedError.name` (+ error tests) (#4344)Trung Dangbefore adoption855e5b1

lines 294–311why, one step back
294 }),
295 it('should throw error matching snapshots', async () => {296 // Defined 404 route297 await expect(parseResponse(client['404'].$get())).rejects.toThrowErrorMatchingInlineSnapshot(298 '[DetailedError: 404 Not Found]'299 )300301 // Defined 500 route302 await expect(parseResponse(client['500'].$get())).rejects.toThrowErrorMatchingInlineSnapshot(303 '[DetailedError: 500 Internal Server Error]'304 )305306 // Not defined route307 // Note: the error in this test case is thrown at the `fetch` call (.$get()), not during the `parseResponse` call, so I think `parseResponse` should not try to catch and wrap it into a structured error, which could be inconsistent, if the user awaited the fetch.308 await expect(309 // @ts-expect-error noRoute is not defined310 parseResponse(client['noRoute'].$get())311 ).rejects.toThrowErrorMatchingInlineSnapshot('[TypeError: fetch failed]')

fix(parseResponse): should not include error responses in result (#4348)Trung Dangbefore adoption08a80e2

lines 312–335why, one step back
312 }),
313 it('(type-only) should bypass error responses in the result type inference - simple 404', async () => {314 type ResultType = Awaited<315 ReturnType<typeof parseResponse<Awaited<ReturnType<(typeof client)['404']['$get']>>>>316 >317 type _verify = Expect<Equal<Awaited<ResultType>, undefined>>318 }),319 it('(type-only) should bypass error responses in the result type inference - conditional - json', async () => {320 type ResultType = Awaited<321 ReturnType<322 typeof parseResponse<Awaited<ReturnType<(typeof client)['might-error-json']['$get']>>>323 >324 >325 type _verify = Expect<Equal<ResultType, { data: { id: number }[] }>>326 }),327 it('(type-only) should bypass error responses in the result type inference - conditional - mixed json/text', async () => {328 type ResultType = Awaited<329 ReturnType<330 typeof parseResponse<331 Awaited<ReturnType<(typeof client)['might-error-mixed-json-text']['$get']>>332 >333 >334 >335 type _verify = Expect<Equal<ResultType, { message: string }>>

Merge pull request #4340 from honojs/nextYusuke Wadabefore adoption3a5248f

lines 336–337why, one step back
336 }),
337 ])

fix(client): Fix `parseResponse` not parsing json in react native (#4399)Igor Zhukovinbefore adoption5b277d8

lines 338–357why, one step back
338
339 it('should parse json response with _bodyInit when body is undefined', async () => {340 const mockFetch = vi.fn().mockResolvedValue({341 ok: true,342 status: 200,343 headers: new Headers({ 'content-type': 'application/json' }),344 body: undefined,345 _bodyInit: '{"message":"test"}',346 json: async () => ({ message: 'test' }),347 })348349 global.fetch = mockFetch350351 const mockClientResponse = {352 $get: mockFetch,353 }354355 const result = await parseResponse(mockClientResponse.$get())356 expect(result).toEqual({ message: 'test' })357 })

chore: format and lint `benchmarks/*` (#4317)Yusuke Wadabefore adoption0d12626

line 358why, one step back
358})