Skip to content
Myr

index.test.ts

This file

Path

src/middleware/timing/index.test.ts

310 lines · 9.6 KiB · TypeScript

Last changed by

chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2

History of this file

Take it

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

Merge commit from forkYusuke Wadabefore adoptionf0b094d

line 1why, one step back
1import { endTime, setMetric, startTime, timing, wrapTime } from '.'

chore: let oxfmt sort imports instead of eslint (#5442)Yusuke Wadabefore adoption859e2c2

line 2why, one step back
2import { Hono } from '../../hono'

Merge commit from forkYusuke Wadabefore adoptionf0b094d

lines 3–310why, one step back
3
4describe('Server-Timing API', () => {5 const app = new Hono()67 const totalDescription = 'my total DescRipTion!'8 const name = 'sleep'9 const region = 'region'10 const regionDesc = 'europe-west3'1112 app.use(13 '*',14 timing({15 totalDescription,16 })17 )18 app.get('/', (c) => c.text('/'))19 app.get('/api', async (c) => {20 startTime(c, name)21 await new Promise((r) => setTimeout(r, 30))22 endTime(c, name)2324 return c.text('api!')25 })26 app.get('/api-wrap', async (c) => {27 await wrapTime(c, name, new Promise((r) => setTimeout(r, 30)))2829 return c.text('api!')30 })31 app.get('/api-wrap-throw', async (c) => {32 try {33 await wrapTime(c, name, new Promise((_, r) => setTimeout(r, 30)))34 } catch (e) {35 return c.text(`error :( ${e}`, 500)36 }3738 return c.text('api!')39 })40 app.get('/cache', async (c) => {41 setMetric(c, region, regionDesc)4243 return c.text('cache!')44 })4546 const sub = new Hono()4748 sub.use(timing())49 sub.get('/', (c) => c.text('sub'))50 app.route('/sub', sub)5152 it('Should contain total duration', async () => {53 const res = await app.request('http://localhost/')54 expect(res).not.toBeNull()55 expect(res.headers.has('server-timing')).toBeTruthy()56 expect(res.headers.get('server-timing')?.includes('total;dur=')).toBeTruthy()57 expect(res.headers.get('server-timing')?.includes(totalDescription)).toBeTruthy()58 })5960 it('Should contain value metrics', async () => {61 const res = await app.request('http://localhost/api')62 expect(res).not.toBeNull()63 expect(res.headers.has('server-timing')).toBeTruthy()64 expect(res.headers.get('server-timing')?.includes(`${name};dur=`)).toBeTruthy()65 expect(res.headers.get('server-timing')?.includes(name)).toBeTruthy()66 })6768 it('Should contain value metrics, wrapped', async () => {69 const res = await app.request('http://localhost/api-wrap')70 expect(res).not.toBeNull()71 expect(res.headers.has('server-timing')).toBeTruthy()72 expect(res.headers.get('server-timing')?.includes(`${name};dur=`)).toBeTruthy()73 expect(res.headers.get('server-timing')?.includes(name)).toBeTruthy()74 })7576 it('Should contain value metrics, wrapped throw', async () => {77 const res = await app.request('http://localhost/api-wrap-throw')78 expect(res).not.toBeNull()79 expect(res.headers.has('server-timing')).toBeTruthy()80 expect(res.status).toBeGreaterThanOrEqual(500)81 expect(res.headers.get('server-timing')?.includes(`${name};dur=`)).toBeTruthy()82 expect(res.headers.get('server-timing')?.includes(name)).toBeTruthy()83 })8485 it('Should contain value-less metrics', async () => {86 const res = await app.request('http://localhost/cache')87 expect(res).not.toBeNull()88 expect(res.headers.has('server-timing')).toBeTruthy()89 expect(90 res.headers.get('server-timing')?.includes(`${region};desc="${regionDesc}"`)91 ).toBeTruthy()92 expect(res.headers.get('server-timing')?.includes(region)).toBeTruthy()93 expect(res.headers.get('server-timing')?.includes(regionDesc)).toBeTruthy()94 })9596 it('Should not be enabled if the main app has the timing middleware', async () => {97 const consoleWarnSpy = vi.spyOn(console, 'warn')98 const res = await app.request('/sub')99 expect(res.status).toBe(200)100 expect(res.headers.has('server-timing')).toBeTruthy()101 expect(res.headers.get('server-timing')?.includes(totalDescription)).toBeTruthy()102 expect(consoleWarnSpy).not.toHaveBeenCalled()103 consoleWarnSpy.mockRestore()104 })105106 describe('Should handle timing options', async () => {107 it('Should handle autoEnd option', async () => {108 const autoEndApp = new Hono()109110 autoEndApp.use('*', timing())111 autoEndApp.get('/', (c) => {112 startTime(c, 'test')113 return c.text('/')114 })115116 const res = await autoEndApp.request('/')117118 expect(res.status).toBe(200)119 expect(res.headers.get('server-timing')).toContain('test;dur=')120121 const disabledAutoEndApp = new Hono()122123 disabledAutoEndApp.use('*', timing({ autoEnd: false }))124 disabledAutoEndApp.get('/', (c) => {125 startTime(c, 'test')126 return c.text('/')127 })128129 const disabledRes = await disabledAutoEndApp.request('/')130131 expect(disabledRes.status).toBe(200)132 expect(disabledRes.headers.get('server-timing')).not.toContain('test;dur=')133 })134135 it('Should use enabled function return value', async () => {136 const enabledApp = new Hono()137 const enabled = vi.fn(() => false)138139 enabledApp.use('*', timing({ enabled }))140 enabledApp.get('/', (c) => c.text('/'))141142 const res = await enabledApp.request('/')143144 expect(res.status).toBe(200)145 expect(enabled).toHaveBeenCalled()146 expect(res.headers.has('server-timing')).toBeFalsy()147 })148149 it('Should handle total false and value-less metrics without description', async () => {150 const metricApp = new Hono()151152 metricApp.use('*', timing({ total: false }))153 metricApp.get('/', (c) => {154 setMetric(c, 'test')155 return c.text('/')156 })157158 const res = await metricApp.request('/')159160 expect(res.status).toBe(200)161 expect(res.headers.get('server-timing')).toBe('test')162 })163 })164165 describe('Should handle crossOrigin setting', async () => {166 it('Should do nothing when crossOrigin is falsy', async () => {167 const crossOriginApp = new Hono()168169 crossOriginApp.use(170 '*',171 timing({172 crossOrigin: false,173 })174 )175176 crossOriginApp.get('/', (c) => c.text('/'))177178 const res = await crossOriginApp.request('http://localhost/')179180 expect(res).not.toBeNull()181 expect(res.headers.has('server-timing')).toBeTruthy()182 expect(res.headers.has('timing-allow-origin')).toBeFalsy()183 })184185 it('Should set Timing-Allow-Origin to * when crossOrigin is true', async () => {186 const crossOriginApp = new Hono()187188 crossOriginApp.use(189 '*',190 timing({191 crossOrigin: true,192 })193 )194195 crossOriginApp.get('/', (c) => c.text('/'))196197 const res = await crossOriginApp.request('http://localhost/')198199 expect(res).not.toBeNull()200 expect(res.headers.has('server-timing')).toBeTruthy()201 expect(res.headers.has('timing-allow-origin')).toBeTruthy()202 expect(res.headers.get('timing-allow-origin')).toBe('*')203 })204205 it('Should set Timing-Allow-Origin to the value of crossOrigin when it is a string', async () => {206 const crossOriginApp = new Hono()207208 crossOriginApp.use(209 '*',210 timing({211 crossOrigin: 'https://example.com',212 })213 )214215 crossOriginApp.get('/', (c) => c.text('/'))216217 const res = await crossOriginApp.request('http://localhost/')218219 expect(res).not.toBeNull()220 expect(res.headers.has('server-timing')).toBeTruthy()221 expect(res.headers.has('timing-allow-origin')).toBeTruthy()222 expect(res.headers.get('timing-allow-origin')).toBe('https://example.com')223 })224225 it('Should set Timing-Allow-Origin to the return value of crossOrigin when it is a function', async () => {226 const crossOriginApp = new Hono()227228 crossOriginApp.use(229 '*',230 timing({231 crossOrigin: (c) => c.req.header('origin') ?? '*',232 })233 )234235 crossOriginApp.get('/', (c) => c.text('/'))236237 const res = await crossOriginApp.request('http://localhost/', {238 headers: {239 origin: 'https://example.com',240 },241 })242243 expect(res).not.toBeNull()244 expect(res.headers.has('server-timing')).toBeTruthy()245 expect(res.headers.has('timing-allow-origin')).toBeTruthy()246 expect(res.headers.get('timing-allow-origin')).toBe('https://example.com')247 })248249 it("Should use Date.now as backup if performance API isn't available", async () => {250 const originalPerformance = globalThis.performance251 // @ts-expect-error disable performance API for testing252 delete globalThis.performance253 const DateNowSpy = vi.spyOn(Date, 'now').mockReturnValue(123456789)254255 const app = new Hono().use(timing()).get('/', (c) => {256 startTime(c, 'test')257 endTime(c, 'test')258 return c.text('hello')259 })260261 const res = await app.request('/')262 expect(res.status).toBe(200)263264 expect(DateNowSpy).toHaveBeenCalled()265266 DateNowSpy.mockRestore()267 globalThis.performance = originalPerformance268 })269 })270271 describe('Configuration validation', async () => {272 it('Should silently warn when no timing metrics are available', async () => {273 const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})274275 const app = new Hono().get('/', (c) => {276 setMetric(c, 'test', 123)277 startTime(c, 'test')278 endTime(c, 'test')279 return c.text('hello')280 })281282 const res = await app.request('/')283 expect(res.status).toBe(200)284285 expect(consoleWarnSpy).toHaveBeenNthCalledWith(286 2,287 'Metrics not initialized! Please add the `timing()` middleware to this route!'288 )289290 consoleWarnSpy.mockRestore()291 })292293 it('Should silently warn when trying to end a non-existent timer', async () => {294 const consoleWarnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {})295296 const app = new Hono().use(timing()).get('/', (c) => {297 setMetric(c, 'region', 'europe-west3')298 endTime(c, 'nonExistentTimer')299 return c.text('hello')300 })301302 const res = await app.request('/')303 expect(res.status).toBe(200)304305 expect(consoleWarnSpy).toHaveBeenCalledWith('Timer "nonExistentTimer" does not exist!')306307 consoleWarnSpy.mockRestore()308 })309 })310})