import { isValidElement, type ReactElement } from 'react' import { describe, expect, test, vi } from 'vitest' vi.mock('next/navigation.js', () => ({ usePathname: () => '/en/missing' })) import { createNotFoundPage, renderNotFoundView } from '../src/modules/frontend/pageRoute.js' import { localeFromPath } from '../src/modules/pages/localeFromPath.js' import { LocaleView } from '../src/modules/pages/LocaleView.js' import { NotFoundLoader } from '../src/modules/pages/NotFoundLoader.js' const layout = [{ id: '1', blockType: 'hero' }] const helpers = () => ({ getConfiguredLocales: vi.fn(async () => ['pl', 'en']), getNotFoundPage: vi.fn(async (locale: string) => ({ layout, locale })), i18n: { defaultLocale: 'pl', locales: [{ code: 'pl' }, { code: 'en' }] }, }) as never as { getNotFoundPage: ReturnType } & Parameters[0] describe('localeFromPath', () => { test('first segment when it is a locale, default otherwise', () => { expect(localeFromPath('/en/missing', ['pl', 'en'], 'pl')).toBe('en') expect(localeFromPath('/de/missing', ['pl', 'en'], 'pl')).toBe('pl') expect(localeFromPath('', ['pl'], 'pl')).toBe('pl') }) }) describe('createNotFoundPage', () => { test('lazy (load): only the loader goes into the payload — no 404 page is read or rendered', async () => { const h = helpers() const load = vi.fn(async () => null) const element = (await createNotFoundPage(h, { load })()) as ReactElement<{ load: unknown; locales: string[] }> expect(element.type).toBe(NotFoundLoader) expect(element.props.locales).toEqual(['pl', 'en']) expect(element.props.load).toBe(load) expect(h.getNotFoundPage).not.toHaveBeenCalled() }) test('eager (blocks): one view per locale in LocaleView', async () => { const h = helpers() const element = (await createNotFoundPage(h, { blocks: {} })()) as ReactElement<{ views: Record }> expect(element.type).toBe(LocaleView) expect(Object.keys(element.props.views)).toEqual(['pl', 'en']) expect(h.getNotFoundPage).toHaveBeenCalledTimes(2) }) }) describe('renderNotFoundView', () => { test('renders the requested configured locale', async () => { const h = helpers() const node = await renderNotFoundView(h, { blocks: {} }, 'en') expect(isValidElement(node)).toBe(true) expect(h.getNotFoundPage).toHaveBeenCalledWith('en') }) test('a locale from the browser outside the configured ones → default locale', async () => { const h = helpers() await renderNotFoundView(h, { blocks: {} }, '../admin') await renderNotFoundView(h, { blocks: {} }, 42) expect(h.getNotFoundPage.mock.calls).toEqual([['pl'], ['pl']]) }) test('no 404 page in the panel → fallback for that locale', async () => { const h = helpers() h.getNotFoundPage.mockResolvedValueOnce(null) expect(await renderNotFoundView(h, { blocks: {}, fallback: (locale) => `missing:${locale}` }, 'en')).toBe('missing:en') }) })