| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114 |
- const assert = require('node:assert/strict');
- const fs = require('node:fs');
- const path = require('node:path');
- const vm = require('node:vm');
- const ts = require('typescript');
- const React = require('react');
- const { renderToStaticMarkup } = require('react-dom/server');
- const root = process.cwd();
- function loader(overrides = {}, globals = {}) {
- const cache = new Map();
- function load(file) {
- file = path.resolve(root, file);
- if (!path.extname(file)) file += fs.existsSync(file + '.tsx') ? '.tsx' : '.ts';
- if (file.endsWith('.json')) return JSON.parse(fs.readFileSync(file, 'utf8'));
- if (cache.has(file)) return cache.get(file);
- const module = { exports: {} }; cache.set(file, module.exports);
- const source = ts.transpileModule(fs.readFileSync(file, 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022 } }).outputText;
- const resolve = spec => {
- if (Object.hasOwn(overrides, spec)) return overrides[spec];
- if (spec.startsWith('@/')) return load('src/' + spec.slice(2));
- if (spec.startsWith('.')) return load(path.resolve(path.dirname(file), spec));
- return require(spec);
- };
- vm.runInNewContext(source, { module, exports: module.exports, require: resolve, ...globals }, { filename: file });
- return module.exports;
- }
- return load;
- }
- const nextMocks = {
- 'next/navigation': { usePathname: () => '/blogs/netherlands-visa-appointments-dublin' },
- 'next/link': props => React.createElement('a', props, props.children),
- '@/lib/auth': { isAdmin: () => false, logout: () => {} },
- };
- const loadSSR = loader(nextMocks);
- const { navigationCopy } = loadSSR('src/lib/blog/translations.ts');
- const locales = ['en', 'de', 'fr', 'es', 'it', 'pt', 'zh'];
- const indexes = locales.map(locale => ({ locale, href: `${locale === 'en' ? '' : '/' + locale}/blogs` }));
- const articles = indexes.map(a => ({ ...a, id: 'netherlands', href: a.href + '/netherlands-' + a.locale }));
- for (const locale of locales) {
- const current = articles.find(a => a.locale === locale);
- const localizedLoad = loader({ ...nextMocks, 'next/navigation': { usePathname: () => current.href } });
- const LocalNavbar = localizedLoad('src/components/blog/BlogNavbar.tsx').default;
- const html = renderToStaticMarkup(React.createElement(LocalNavbar, { locale, indexes, articles }));
- assert([...html.matchAll(/<option[^>]+>/g)].some(([tag]) => tag.includes(`value="${current.href}"`) && tag.includes('selected=""')), 'Current article must be selected');
- for (const href of [locale === 'en' ? '/' : '/' + locale, indexes.find(a => a.locale === locale).href, ...['/services', '/slots', '/login'].map(path => (locale === 'en' ? '' : '/' + locale) + path)]) assert(html.includes(`href="${href}"`));
- assert(html.includes(`lang="${locale}"`) && html.includes('aria-expanded="false"'));
- assert(html.includes('<select') && !html.includes('article language stays unchanged'));
- assert(html.includes('w-24 sm:w-auto') && html.includes('hidden xl:flex'), 'Blog navigation needs a readable mobile selector and wider desktop breakpoint');
- for (const a of articles) assert(html.includes(`value="${a.href}"`), 'Missing counterpart');
- assert(!html.includes('nav.services'), 'Untranslated navigation key');
- for (const key of ['nav.services', 'nav.slots', 'nav.blogs', 'nav.login']) assert(html.includes(navigationCopy[locale][key]), `Missing localized label: ${locale}/${key}`);
- }
- // Exercise the actual selector handler with explicit pathname fixtures.
- for (const current of [indexes[0], articles[0], indexes[6], articles[6]]) {
- let assigned;
- const load = loader({ ...nextMocks, 'next/navigation': { usePathname: () => current.href } }, { window: { location: { assign: href => assigned = href } } });
- const tree = load('src/components/blog/BlogNavbar.tsx').default({ locale: current.locale, indexes, articles });
- const nav = tree.props.children.props.children;
- const selector = nav.props.languageControl;
- const expected = 'id' in current ? articles : indexes;
- assert.equal(selector.props.value, current.href);
- assert.deepEqual(selector.props.children.map(option => option.props.value), expected.map(a => a.href));
- selector.props.onChange({ target: { value: expected[1].href } });
- assert.equal(assigned, expected[1].href);
- }
- // Simulated provider hooks test browser-preference isolation and document-language ownership.
- function providerCase(options, expectedDefault, detect) {
- const state = []; const effects = []; let index = 0; let reads = 0; const writes = [];
- const fakeReact = { ...React, useCallback: fn => fn, useMemo: fn => fn(),
- createContext: () => ({ Provider: 'context-provider' }),
- useState: initial => { const i = index++; if (!(i in state)) state[i] = initial; return [state[i], value => { state[i] = value; }]; },
- useEffect: callback => effects.push(callback),
- };
- const document = { documentElement: { lang: 'en' } };
- const load = loader({ react: fakeReact }, { document, navigator: { language: 'zh-CN' }, localStorage: { getItem: () => { reads++; return expectedDefault === 'en' ? 'zh' : 'en'; }, setItem: (...args) => writes.push(args) } });
- const Provider = load('src/lib/i18n/LanguageContext.tsx').LanguageProvider;
- const element = Provider({ children: null, ...options });
- assert.equal(element.props.value.lang, expectedDefault);
- effects.forEach(fn => fn());
- assert.equal(reads > 0, detect);
- assert.equal(state[0], 'en', 'Homepage honors stored English; blog ignores stored Chinese');
- element.props.value.setLang('zh');
- assert.equal(state[0], 'zh');
- assert.deepEqual(writes[0], ['app_lang', 'zh']);
- assert.equal(document.documentElement.lang, options.updateDocumentLanguage === false ? 'en' : 'zh-CN');
- }
- providerCase({ initialLang: 'en', detectPreference: false, updateDocumentLanguage: false }, 'en', false);
- providerCase({}, 'zh', true);
- // Simulated shared-Navbar hooks cover mobile/auth branches without a browser or real session.
- for (const [logged, admin, open] of [[false, false, false], [false, false, true], [true, false, true], [true, true, true]]) {
- let index = 0; const states = [logged, admin, open]; const effects = []; const changes = []; let logoutCalls = 0; const events = [];
- const fakeReact = { ...React, useRef: () => ({current:null}), useCallback: fn => fn, useMemo: fn => fn(), useState: () => { const i = index++; return [states[i], value => changes.push([i, value])]; }, useEffect: callback => effects.push(callback) };
- const load = loader({ ...nextMocks, react: fakeReact,
- '@/lib/i18n/LanguageContext': { useLanguage: () => ({ t: key => key.split('.').pop(), lang: 'en', setLang: () => {} }) },
- '@/lib/auth': { isAdmin: () => admin, logout: () => { logoutCalls++; } },
- }, { localStorage: { getItem: () => logged ? 'test-session-marker' : null }, window: { addEventListener: (name, callback) => events.push([name, callback]), removeEventListener: () => {} } });
- const tree = load('src/components/Navbar.tsx').default({ showBlog: true, blogHref: '/blogs', navigationLanguageOnly: true });
- const nodes = [];
- function visit(node) { if (Array.isArray(node)) return node.forEach(visit); if (!node || typeof node !== 'object') return; nodes.push(node); visit(node.props?.children); }
- visit(tree);
- for (const href of ['/blogs', '/services', '/slots', logged ? '/dashboard' : '/login']) assert(nodes.some(n => n.props?.href === href));
- assert.equal(nodes.some(n => n.props?.href === '/admin'), logged && admin);
- assert.equal(nodes.some(n => n.props?.id === 'site-mobile-menu'), open);
- const toggle = nodes.find(n => n.props?.['aria-controls'] === 'site-mobile-menu');
- assert.equal(toggle.props['aria-expanded'], open); toggle.props.onClick();
- assert(changes.some(([i, value]) => i === 2 && value === !open));
- effects.forEach(fn => fn()); assert(events.some(([name]) => name === 'storage'));
- assert(changes.some(([i, value]) => i === 0 && value === logged));
- if (logged) { nodes.find(n => n.props?.title === 'logout').props.onClick(); assert.equal(logoutCalls, 1); assert(changes.some(([i, value]) => i === 2 && value === false)); }
- if (open) { nodes.find(n => n.props?.className?.includes('fixed inset-0')).props.onClick(); assert(changes.some(([i, value]) => i === 2 && value === false)); }
- }
- console.log('PASS: shared navbar SSR links/actions and seven-language labels/counterpart selection; provider defaults and document-language isolation; simulated mobile toggle/overlay and logged-out/user/admin/logout/storage branches. This is not browser interaction or authenticated end-to-end QA.');
|