import { describe, it, expect, beforeEach } from 'vitest'; import i18n from '../i18n'; // i18n.ts already initialized this shared instance as a module-scope side // effect when it was first imported (simulating "the library loaded first"). // These tests simulate the opposite/merge scenario: an app that has already // called i18n.init() with its own custom resources, followed by the library // merging its defaults in via the same addResourceBundle(..., true, false) // call used by the guarded branch in i18n.ts. describe('i18next singleton merge behavior', () => { beforeEach(async () => { await i18n.changeLanguage('pt-BR'); }); it('is already initialized by the time i18n.ts has been imported', () => { expect(i18n.isInitialized).toBe(true); }); it('preserves an app-customized key when the library merges its defaults with overwrite: false', () => { // Simulate the app registering a customized string before the library's // guarded init runs its `else` branch. i18n.addResourceBundle('pt-BR', 'translation', { home: { welcome: 'Custom Welcome' } }, true, true); expect(i18n.t('home.welcome')).toBe('Custom Welcome'); // Simulate the library's merge branch: it must not clobber the app's key, // even though its own default bundle also defines `home.welcome`. It must // still add a genuinely new key the app never defined. i18n.addResourceBundle( 'pt-BR', 'translation', { home: { welcome: 'Bem-vindo ao Design System!', mergeOnlyKey: 'Default merge value' } }, true, false ); expect(i18n.t('home.welcome')).toBe('Custom Welcome'); // Keys the app never defined should still be filled in by the merge. expect(i18n.t('home.mergeOnlyKey')).toBe('Default merge value'); }); it('would silently overwrite the app key if overwrite were true (regression guard)', () => { i18n.addResourceBundle('pt-BR', 'translation', { home: { welcome: 'Custom Welcome' } }, true, true); expect(i18n.t('home.welcome')).toBe('Custom Welcome'); // This mirrors the *bug* the guard prevents — kept here only to document // why `overwrite: false` is required in the real merge branch. i18n.addResourceBundle( 'pt-BR', 'translation', { home: { welcome: 'Bem-vindo ao Design System!' } }, true, true ); expect(i18n.t('home.welcome')).toBe('Bem-vindo ao Design System!'); }); });