Skip to content
Myr

index.test.ts

This file

Path

src/middleware/language/index.test.ts

552 lines 路 14.9 KiB 路 TypeScript

Last changed by

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

History of this file

Take it

1import { languageDetector } from '.'2import { Hono } from '../../hono'3import { DEFAULT_OPTIONS, detectors, normalizeLanguage } from './language'45describe('languageDetector', () => {6  const createTestApp = (options = {}) => {7    const app = new Hono()89    app.use('/*', languageDetector(options))1011    app.get('/*', (c) => c.text(c.get('language')))1213    return app14  }1516  describe('Query Parameter Detection', () => {17    it('should detect language from query parameter', async () => {18      const app = createTestApp({19        supportedLanguages: ['en', 'fr', 'es'],20        fallbackLanguage: 'en',21      })2223      const res = await app.request('/?lang=fr')24      expect(await res.text()).toBe('fr')25    })2627    it('should ignore unsupported languages in query', async () => {28      const app = createTestApp({29        supportedLanguages: ['en', 'fr'],30        fallbackLanguage: 'en',31      })3233      const res = await app.request('/?lang=de')34      expect(await res.text()).toBe('en')35    })36  })3738  describe('Cookie Detection', () => {39    it('should detect language from cookie', async () => {40      const app = createTestApp({41        supportedLanguages: ['en', 'fr'],42        fallbackLanguage: 'en',43      })4445      const res = await app.request('/', {46        headers: {47          cookie: 'language=fr',48        },49      })50      expect(await res.text()).toBe('fr')51    })5253    it('should cache detected language in cookie when enabled', async () => {54      const app = createTestApp({55        supportedLanguages: ['en', 'fr'],56        fallbackLanguage: 'en',57        caches: ['cookie'],58      })5960      const res = await app.request('/?lang=fr')61      expect(res.headers.get('set-cookie')).toContain('language=fr')62    })63  })6465  describe('Header Detection', () => {66    it('should detect language from Accept-Language header', async () => {67      const app = createTestApp({68        supportedLanguages: ['en', 'fr', 'es'],69        fallbackLanguage: 'en',70      })7172      const res = await app.request('/', {73        headers: {74          'accept-language': 'fr-FR,fr;q=0.9,en;q=0.8',75        },76      })77      expect(await res.text()).toBe('fr')78    })7980    it('should fallback to language code when locale code is not in supportedLanguages', async () => {81      const app = createTestApp({82        supportedLanguages: ['en', 'ja'],83        fallbackLanguage: 'en',84        order: ['header'],85      })8687      const res = await app.request('/', {88        headers: {89          'accept-language': 'ja-JP',90        },91      })92      expect(await res.text()).toBe('ja')93    })9495    it('should not detect a language explicitly rejected with q=0', async () => {96      const app = createTestApp({97        supportedLanguages: ['fr', 'en'],98        fallbackLanguage: 'en',99        order: ['header'],100      })101102      const res = await app.request('/', {103        headers: {104          'accept-language': 'fr;q=0',105        },106      })107      expect(await res.text()).toBe('en')108    })109110    it('should skip q=0 languages before falling back to the default', async () => {111      const app = createTestApp({112        supportedLanguages: ['fr', 'en'],113        fallbackLanguage: 'en',114        order: ['header'],115      })116117      const res = await app.request('/', {118        headers: {119          'accept-language': 'fr;q=0,de;q=0.8',120        },121      })122      expect(await res.text()).toBe('en')123    })124125    it('should continue to the next detector after a zero-quality language', async () => {126      const app = createTestApp({127        supportedLanguages: ['fr', 'en', 'ja'],128        fallbackLanguage: 'en',129        order: ['header', 'querystring'],130      })131132      const res = await app.request('/?lang=ja', {133        headers: { 'accept-language': 'fr;q=0' },134      })135      expect(await res.text()).toBe('ja')136      expect(res.headers.get('set-cookie')).toContain('language=ja')137    })138139    it('should match after multiple truncations', async () => {140      const app = createTestApp({141        supportedLanguages: ['zh-Hant', 'en'],142        fallbackLanguage: 'en',143        order: ['header'],144      })145146      const res = await app.request('/', {147        headers: {148          'accept-language': 'zh-Hant-CN',149        },150      })151      expect(await res.text()).toBe('zh-Hant')152    })153154    it('should select the longest truncated match regardless of supported language order', async () => {155      const app = createTestApp({156        supportedLanguages: ['zh', 'zh-Hant'],157        fallbackLanguage: 'zh',158        order: ['header'],159      })160161      const res = await app.request('/', {162        headers: {163          'accept-language': 'zh-Hant-CN',164        },165      })166      expect(await res.text()).toBe('zh-Hant')167    })168169    it('should fallback when truncation does not match any supported language', async () => {170      const app = createTestApp({171        supportedLanguages: ['en', 'ja'],172        fallbackLanguage: 'en',173        order: ['header'],174      })175176      const res = await app.request('/', {177        headers: {178          'accept-language': 'ko-KR',179        },180      })181      expect(await res.text()).toBe('en')182    })183184    it('should prefer exact match over truncated match', async () => {185      const app = createTestApp({186        supportedLanguages: ['fr', 'fr-CA'],187        fallbackLanguage: 'fr',188        order: ['header'],189      })190191      const res = await app.request('/', {192        headers: {193          'accept-language': 'fr-CA',194        },195      })196      expect(await res.text()).toBe('fr-CA')197    })198199    it('should handle case-insensitive truncation matching', async () => {200      const app = createTestApp({201        supportedLanguages: ['en', 'ja'],202        fallbackLanguage: 'en',203        order: ['header'],204        ignoreCase: true,205      })206207      const res = await app.request('/', {208        headers: {209          'accept-language': 'JA-JP',210        },211      })212      expect(await res.text()).toBe('ja')213    })214215    it('should handle malformed Accept-Language headers', async () => {216      const app = createTestApp({217        supportedLanguages: ['en', 'fr'],218        fallbackLanguage: 'en',219      })220221      const res = await app.request('/', {222        headers: {223          'accept-language': 'invalid;header;;format',224        },225      })226      expect(await res.text()).toBe('en')227    })228229    it('should handle invalid header lookup key gracefully', async () => {230      const app = createTestApp({231        order: ['header'],232        lookupFromHeaderKey: 'accept\nlanguage',233        supportedLanguages: ['en', 'fr'],234        fallbackLanguage: 'en',235      })236237      const res = await app.request('/', {238        headers: {239          'accept-language': 'fr',240        },241      })242243      expect(await res.text()).toBe('en')244    })245  })246247  describe('Language Normalization', () => {248    it('should preserve the configured value for a case-insensitive truncated match', () => {249      expect(250        normalizeLanguage('zh-HANT-CN', {251          ...DEFAULT_OPTIONS,252          supportedLanguages: ['en', 'ZH-Hant'],253        })254      ).toBe('ZH-Hant')255    })256257    it('should handle a large unsupported language tag', () => {258      const unsupportedLanguage = 'x-'.repeat(30_000).slice(0, -1)259260      expect(261        normalizeLanguage(unsupportedLanguage, {262          ...DEFAULT_OPTIONS,263          supportedLanguages: ['en', 'ja'],264        })265      ).toBeUndefined()266    })267  })268269  describe('Path Detection', () => {270    it('should detect language from path', async () => {271      const app = createTestApp({272        order: ['path'],273        supportedLanguages: ['en', 'fr'],274        fallbackLanguage: 'en',275        lookupFromPathIndex: 0,276      })277278      const res = await app.request('/fr/page')279      expect(await res.text()).toBe('fr')280    })281282    it('should handle invalid path index gracefully', async () => {283      const app = createTestApp({284        order: ['path'],285        supportedLanguages: ['en', 'fr'],286        fallbackLanguage: 'en',287        lookupFromPathIndex: 99,288      })289290      const res = await app.request('/fr/page')291      expect(await res.text()).toBe('en')292    })293294    it('should detect language from original URL when getPath modifies the path', async () => {295      const app = new Hono({296        getPath: (req) => {297          const url = new URL(req.url)298          let pathname = url.pathname299          // Remove language prefix /fr/300          if (pathname.startsWith('/fr/')) {301            pathname = pathname.replace('/fr/', '/')302          }303          return pathname304        },305      })306307      app.use(308        '*',309        languageDetector({310          order: ['path'],311          supportedLanguages: ['en', 'fr'],312          fallbackLanguage: 'en',313          lookupFromPathIndex: 0,314        })315      )316317      app.get('/home', (c) => c.text(c.get('language')))318319      const res = await app.request('/fr/home')320      expect(await res.text()).toBe('fr')321    })322  })323324  describe('Detection Order', () => {325    it('should respect detection order', async () => {326      const app = createTestApp({327        order: ['cookie', 'querystring'],328        supportedLanguages: ['en', 'fr', 'es'],329        fallbackLanguage: 'en',330      })331332      const res = await app.request('/?lang=fr', {333        headers: {334          cookie: 'language=es',335        },336      })337338      // Since cookie is first in order, it should use 'es'339      expect(await res.text()).toBe('es')340    })341342    it('should fall back to next detector if first fails', async () => {343      const app = createTestApp({344        order: ['cookie', 'querystring'],345        supportedLanguages: ['en', 'fr'],346        fallbackLanguage: 'en',347      })348349      const res = await app.request('/?lang=fr') // No cookie350      expect(await res.text()).toBe('fr') // Should use querystring351    })352  })353354  describe('Language Conversion', () => {355    it('should apply language conversion function', async () => {356      const app = createTestApp({357        supportedLanguages: ['en', 'fr'],358        fallbackLanguage: 'en',359        convertDetectedLanguage: (lang: string) => lang.split('-')[0],360      })361362      const res = await app.request('/?lang=fr-FR')363      expect(await res.text()).toBe('fr')364    })365366    it('should handle case sensitivity according to options', async () => {367      const app = createTestApp({368        supportedLanguages: ['en', 'fr'],369        fallbackLanguage: 'en',370        ignoreCase: false,371      })372373      const res = await app.request('/?lang=FR')374      expect(await res.text()).toBe('en') // Falls back because case doesn't match375    })376  })377378  describe('Error Handling', () => {379    it('should fall back to default language on error', async () => {380      const app = createTestApp({381        supportedLanguages: ['en', 'fr'],382        fallbackLanguage: 'en',383      })384385      const detector = vi.spyOn(detectors, 'querystring').mockImplementation(() => {386        throw new Error('Simulated error')387      })388389      const res = await app.request('/?lang=fr')390      expect(await res.text()).toBe('en')391392      detector.mockRestore()393    })394395    it('should handle missing cookie values gracefully', async () => {396      const app = createTestApp({397        supportedLanguages: ['en', 'fr'],398        fallbackLanguage: 'en',399        order: ['cookie'],400      })401402      const res = await app.request('/')403      expect(await res.text()).toBe('en')404    })405406    it('should handle errors in convertDetectedLanguage function', async () => {407      const app = createTestApp({408        supportedLanguages: ['en', 'fr'],409        fallbackLanguage: 'en',410        convertDetectedLanguage: (lang: string) => {411          if (lang === 'fr') {412            throw new Error('Simulated error in convertDetectedLanguage')413          }414          return lang415        },416      })417418      const res = await app.request('/?lang=fr')419      expect(await res.text()).toBe('en')420    })421  })422423  describe('Configuration Validation', () => {424    it('should throw if fallback language is not in supported languages', () => {425      expect(() => {426        createTestApp({427          supportedLanguages: ['fr', 'es'],428          fallbackLanguage: 'en',429        })430      }).toThrow()431    })432433    it('should throw if path index is negative', () => {434      expect(() => {435        createTestApp({436          lookupFromPathIndex: -1,437        })438      }).toThrow()439    })440441    it('should handle empty supported languages list', () => {442      expect(() => {443        createTestApp({444          supportedLanguages: [],445        })446      }).toThrow()447    })448449    it('should handle invalid order option', async () => {450      expect(() => {451        createTestApp({452          order: ['invalidDetector' as any],453        })454      }).toThrow()455    })456457    it('should handle early return for caches', async () => {458      const app = createTestApp({459        caches: ['test'],460        supportedLanguages: ['en'],461      })462463      const res = await app.request('/?lang=en')464465      expect(await res.text()).toBe('en')466      expect(res.headers.get('set-cookie')).toBeNull()467    })468  })469470  describe('Debug Mode', () => {471    it('should log errors in debug mode', async () => {472      const consoleErrorSpy = vi.spyOn(console, 'error')473474      const app = createTestApp({475        supportedLanguages: ['en', 'fr'],476        fallbackLanguage: 'en',477        debug: true,478      })479480      const detector = vi.spyOn(detectors, 'querystring').mockImplementation(() => {481        throw new Error('Simulated error')482      })483484      await app.request('/?lang=fr')485486      expect(consoleErrorSpy).toHaveBeenCalledWith(487        'Error in querystring detector:',488        expect.any(Error)489      )490491      detector.mockRestore()492      consoleErrorSpy.mockRestore()493    })494495    // The log test remains unchanged496    it('should log debug information when enabled', async () => {497      const consoleSpy = vi.spyOn(console, 'log')498499      const app = createTestApp({500        supportedLanguages: ['en', 'fr'],501        fallbackLanguage: 'en',502        debug: true,503      })504505      await app.request('/?lang=fr')506507      expect(consoleSpy).toHaveBeenCalledWith(508        expect.stringContaining('Language detected from querystring')509      )510511      consoleSpy.mockRestore()512    })513514    it('should handle cookie cache errors in debug mode', async () => {515      const consoleErrorSpy = vi.spyOn(console, 'error')516517      const app = createTestApp({518        supportedLanguages: ['en', 'fr'],519        fallbackLanguage: 'en',520        caches: ['cookie'],521        lookupCookie: 'bad cookie',522        debug: true,523      })524525      const res = await app.request('/?lang=fr')526527      expect(await res.text()).toBe('fr')528      expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to cache language:', expect.any(Error))529530      consoleErrorSpy.mockRestore()531    })532533    it('should silently handle cookie cache errors when debug mode is disabled', async () => {534      const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})535536      const app = createTestApp({537        supportedLanguages: ['en', 'fr'],538        fallbackLanguage: 'en',539        caches: ['cookie'],540        lookupCookie: 'bad cookie',541        debug: false,542      })543544      const res = await app.request('/?lang=fr')545546      expect(await res.text()).toBe('fr')547      expect(consoleErrorSpy).not.toHaveBeenCalled()548549      consoleErrorSpy.mockRestore()550    })551  })552})