Skip to content

Commit

Permalink
test: useI18n 100% coverage (#17)
Browse files Browse the repository at this point in the history
  • Loading branch information
QuiiBz authored Jul 29, 2022
1 parent 2634d0d commit 21b0cab
Show file tree
Hide file tree
Showing 2 changed files with 64 additions and 9 deletions.
69 changes: 63 additions & 6 deletions packages/next-international/__tests__/use-i18n.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,11 +6,20 @@ import en from './utils/en';

beforeEach(() => {
vi.mock('next/router', () => ({
useRouter: vi.fn().mockImplementation(() => ({
locale: 'en',
defaultLocale: 'en',
locales: ['en', 'fr'],
})),
useRouter: vi
.fn()
.mockImplementationOnce(() => ({
locales: ['en', 'fr'],
}))
.mockImplementationOnce(() => ({
locale: 'en',
defaultLocale: 'en',
}))
.mockImplementation(() => ({
locale: 'en',
defaultLocale: 'en',
locales: ['en', 'fr'],
})),
}));
});

Expand All @@ -19,7 +28,55 @@ afterEach(() => {
});

describe('useI18n', () => {
it('should thrown if not used inside I18nProvider', () => {
it('should log error if locale not set in next.config.js', () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => null);
const { useI18n, I18nProvider } = createI18n<typeof import('./utils/en').default>({
en: () => import('./utils/en'),
fr: () => import('./utils/fr'),
});

function App() {
const { t } = useI18n();

return <p>{t('hello')}</p>;
}

render(
<I18nProvider locale={en}>
<App />
</I18nProvider>,
);
expect(console.error).toHaveBeenCalledWith(
"[next-international] 'i18n.defaultLocale' not defined in 'next.config.js'",
);

spy.mockReset();
});

it('should log error if locales not set in next.config.js', () => {
const spy = vi.spyOn(console, 'error').mockImplementation(() => null);
const { useI18n, I18nProvider } = createI18n<typeof import('./utils/en').default>({
en: () => import('./utils/en'),
fr: () => import('./utils/fr'),
});

function App() {
const { t } = useI18n();

return <p>{t('hello')}</p>;
}

render(
<I18nProvider locale={en}>
<App />
</I18nProvider>,
);
expect(console.error).toHaveBeenCalledWith("[next-international] 'i18n.locales' not defined in 'next.config.js'");

spy.mockReset();
});

it('should throw if not used inside I18nProvider', () => {
const { useI18n } = createI18n<typeof import('./utils/en').default>({
en: () => import('./utils/en'),
fr: () => import('./utils/fr'),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -46,9 +46,7 @@ export function createI18nProvider<Locale extends BaseLocale>(
return;
}

const load = locales[locale] || locales[defaultLocale];

load().then(content => {
locales[locale]().then(content => {
setClientLocale(content.default as Locale);
});
}, [locale, defaultLocale]);
Expand Down

0 comments on commit 21b0cab

Please sign in to comment.