Skip to content
Myr

refactor(language): Test/improve tests on languages middleware (#4980)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

* test(language): add some tests on the language-middleware * feat: remove unreachable code - detectFromQuery: c.req.query shouldn't throw and normalizeLanguage already has a try/catch that return undefined - detectFromCookie: getCookie shoundn't throw and normalizeLanguage already has a try/catch that return undefined * feat: remove unreachable code - language detector: remove redundant guards and fallback catches handled by detector validation and normalizeLanguage * feat: remove unreachable code - detectLanguage: detector shouldn't be undefined because options are validated before detection * feat: remove unreachable code - languageDetector: detectLanguage shouldn't throw because detector errors are already handled internally

authored by Valère · committed by GitHub · parent 413d3cb · Browse files · 2 files+101 added−33 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

2 files+101 added−33 removed

  • tests:+91 added−0 removed
  • other:+10 added−33 removed

2 files+101 added−33 removed

modified:src/middleware/language/index.test.ts+91 added
164 unmodified lines
165 },166 })167 expect(await res.text()).toBe('en')168 })169170 it('should handle invalid header lookup key gracefully', async () => {171 const app = createTestApp({172 order: ['header'],173 lookupFromHeaderKey: 'accept\nlanguage',174 supportedLanguages: ['en', 'fr'],175 fallbackLanguage: 'en',176 })177178 const res = await app.request('/', {179 headers: {180 'accept-language': 'fr',181 },182 })183184 expect(await res.text()).toBe('en')185 })186 })187188 describe('Path Detection', () => {189 it('should detect language from path', async () => {
130 unmodified lines
320321 const res = await app.request('/')322 expect(await res.text()).toBe('en')323 })324325 it('should handle errors in convertDetectedLanguage function', async () => {326 const app = createTestApp({327 supportedLanguages: ['en', 'fr'],328 fallbackLanguage: 'en',329 convertDetectedLanguage: (lang: string) => {330 if (lang === 'fr') {331 throw new Error('Simulated error in convertDetectedLanguage')332 }333 return lang334 },335 })336337 const res = await app.request('/?lang=fr')338 expect(await res.text()).toBe('en')339 })340 })341342 describe('Configuration Validation', () => {343 it('should throw if fallback language is not in supported languages', () => {
19 unmodified lines
363 supportedLanguages: [],364 })365 }).toThrow()366 })367368 it('should handle invalid order option', async () => {369 expect(() => {370 createTestApp({371 order: ['invalidDetector' as any],372 })373 }).toThrow()374 })375376 it('should handle early return for caches', async () => {377 const app = createTestApp({378 caches: ['test'],379 supportedLanguages: ['en'],380 })381382 const res = await app.request('/?lang=en')383384 expect(await res.text()).toBe('en')385 expect(res.headers.get('set-cookie')).toBeNull()386 })387 })388389 describe('Debug Mode', () => {390 it('should log errors in debug mode', async () => {
37 unmodified lines
428 )429430 consoleSpy.mockRestore()431 })432433 it('should handle cookie cache errors in debug mode', async () => {434 const consoleErrorSpy = vi.spyOn(console, 'error')435436 const app = createTestApp({437 supportedLanguages: ['en', 'fr'],438 fallbackLanguage: 'en',439 caches: ['cookie'],440 lookupCookie: 'bad cookie',441 debug: true,442 })443444 const res = await app.request('/?lang=fr')445446 expect(await res.text()).toBe('fr')447 expect(consoleErrorSpy).toHaveBeenCalledWith('Failed to cache language:', expect.any(Error))448449 consoleErrorSpy.mockRestore()450 })451452 it('should silently handle cookie cache errors when debug mode is disabled', async () => {453 const consoleErrorSpy = vi.spyOn(console, 'error').mockImplementation(() => {})454455 const app = createTestApp({456 supportedLanguages: ['en', 'fr'],457 fallbackLanguage: 'en',458 caches: ['cookie'],459 lookupCookie: 'bad cookie',460 debug: false,461 })462463 const res = await app.request('/?lang=fr')464465 expect(await res.text()).toBe('fr')466 expect(consoleErrorSpy).not.toHaveBeenCalled()467468 consoleErrorSpy.mockRestore()469 })470 })471})
modified:src/middleware/language/language.ts+10 added-33 removed
124 unmodified lines
125/**126 * Detects language from query parameter127 */128export const detectFromQuery = (c: Context, options: DetectorOptions): string | undefined => {129 try {130 const query = c.req.query(options.lookupQueryString)131 return normalizeLanguage(query, options)129 const query = c.req.query(options.lookupQueryString)130 return normalizeLanguage(query, options)132 } catch {133 return undefined134 }131}132133/**134 * Detects language from cookie135 */136export const detectFromCookie = (c: Context, options: DetectorOptions): string | undefined => {141 try {142 const cookie = getCookie(c, options.lookupCookie)143 return normalizeLanguage(cookie, options)137 const cookie = getCookie(c, options.lookupCookie)138 return normalizeLanguage(cookie, options)144 } catch {145 return undefined146 }139}140141/**142 * Detects language from Accept-Language header
21 unmodified lines
164/**165 * Detects language from URL path166 */167export function detectFromPath(c: Context, options: DetectorOptions): string | undefined {176 try {177 const url = new URL(c.req.url)178 const pathSegments = url.pathname.split('/').filter(Boolean)179 const langSegment = pathSegments[options.lookupFromPathIndex]180 return normalizeLanguage(langSegment, options)168 const url = new URL(c.req.url)169 const pathSegments = url.pathname.split('/').filter(Boolean)170 const langSegment = pathSegments[options.lookupFromPathIndex]171 return normalizeLanguage(langSegment, options)181 } catch {182 return undefined183 }172}173174/**175 * Collection of all language detection strategies
54 unmodified lines
230 let detectedLang: string | undefined231232 for (const detectorName of options.order) {233 const detector = detectors[detectorName]246 if (!detector) {247 continue248 }234235 try {236 detectedLang = detector(c, options)237 if (detectedLang) {
36 unmodified lines
274275 validateOptions(options)276277 return async function languageDetector(ctx, next) {293 try {294 const lang = detectLanguage(ctx, options)295 ctx.set('language', lang)278 const lang = detectLanguage(ctx, options)279 ctx.set('language', lang)296 } catch (error) {297 if (options.debug) {298 console.error('Language detection failed:', error)299 }300 ctx.set('language', options.fallbackLanguage)301 }302280 await next()281 }282}