check-blog-nav.cjs 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114
  1. const assert = require('node:assert/strict');
  2. const fs = require('node:fs');
  3. const path = require('node:path');
  4. const vm = require('node:vm');
  5. const ts = require('typescript');
  6. const React = require('react');
  7. const { renderToStaticMarkup } = require('react-dom/server');
  8. const root = process.cwd();
  9. function loader(overrides = {}, globals = {}) {
  10. const cache = new Map();
  11. function load(file) {
  12. file = path.resolve(root, file);
  13. if (!path.extname(file)) file += fs.existsSync(file + '.tsx') ? '.tsx' : '.ts';
  14. if (file.endsWith('.json')) return JSON.parse(fs.readFileSync(file, 'utf8'));
  15. if (cache.has(file)) return cache.get(file);
  16. const module = { exports: {} }; cache.set(file, module.exports);
  17. const source = ts.transpileModule(fs.readFileSync(file, 'utf8'), { compilerOptions: { module: ts.ModuleKind.CommonJS, esModuleInterop: true, jsx: ts.JsxEmit.ReactJSX, target: ts.ScriptTarget.ES2022 } }).outputText;
  18. const resolve = spec => {
  19. if (Object.hasOwn(overrides, spec)) return overrides[spec];
  20. if (spec.startsWith('@/')) return load('src/' + spec.slice(2));
  21. if (spec.startsWith('.')) return load(path.resolve(path.dirname(file), spec));
  22. return require(spec);
  23. };
  24. vm.runInNewContext(source, { module, exports: module.exports, require: resolve, ...globals }, { filename: file });
  25. return module.exports;
  26. }
  27. return load;
  28. }
  29. const nextMocks = {
  30. 'next/navigation': { usePathname: () => '/blogs/netherlands-visa-appointments-dublin' },
  31. 'next/link': props => React.createElement('a', props, props.children),
  32. '@/lib/auth': { isAdmin: () => false, logout: () => {} },
  33. };
  34. const loadSSR = loader(nextMocks);
  35. const { navigationCopy } = loadSSR('src/lib/blog/translations.ts');
  36. const locales = ['en', 'de', 'fr', 'es', 'it', 'pt', 'zh'];
  37. const indexes = locales.map(locale => ({ locale, href: `${locale === 'en' ? '' : '/' + locale}/blogs` }));
  38. const articles = indexes.map(a => ({ ...a, id: 'netherlands', href: a.href + '/netherlands-' + a.locale }));
  39. for (const locale of locales) {
  40. const current = articles.find(a => a.locale === locale);
  41. const localizedLoad = loader({ ...nextMocks, 'next/navigation': { usePathname: () => current.href } });
  42. const LocalNavbar = localizedLoad('src/components/blog/BlogNavbar.tsx').default;
  43. const html = renderToStaticMarkup(React.createElement(LocalNavbar, { locale, indexes, articles }));
  44. assert([...html.matchAll(/<option[^>]+>/g)].some(([tag]) => tag.includes(`value="${current.href}"`) && tag.includes('selected=""')), 'Current article must be selected');
  45. 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}"`));
  46. assert(html.includes(`lang="${locale}"`) && html.includes('aria-expanded="false"'));
  47. assert(html.includes('<select') && !html.includes('article language stays unchanged'));
  48. assert(html.includes('w-24 sm:w-auto') && html.includes('hidden xl:flex'), 'Blog navigation needs a readable mobile selector and wider desktop breakpoint');
  49. for (const a of articles) assert(html.includes(`value="${a.href}"`), 'Missing counterpart');
  50. assert(!html.includes('nav.services'), 'Untranslated navigation key');
  51. for (const key of ['nav.services', 'nav.slots', 'nav.blogs', 'nav.login']) assert(html.includes(navigationCopy[locale][key]), `Missing localized label: ${locale}/${key}`);
  52. }
  53. // Exercise the actual selector handler with explicit pathname fixtures.
  54. for (const current of [indexes[0], articles[0], indexes[6], articles[6]]) {
  55. let assigned;
  56. const load = loader({ ...nextMocks, 'next/navigation': { usePathname: () => current.href } }, { window: { location: { assign: href => assigned = href } } });
  57. const tree = load('src/components/blog/BlogNavbar.tsx').default({ locale: current.locale, indexes, articles });
  58. const nav = tree.props.children.props.children;
  59. const selector = nav.props.languageControl;
  60. const expected = 'id' in current ? articles : indexes;
  61. assert.equal(selector.props.value, current.href);
  62. assert.deepEqual(selector.props.children.map(option => option.props.value), expected.map(a => a.href));
  63. selector.props.onChange({ target: { value: expected[1].href } });
  64. assert.equal(assigned, expected[1].href);
  65. }
  66. // Simulated provider hooks test browser-preference isolation and document-language ownership.
  67. function providerCase(options, expectedDefault, detect) {
  68. const state = []; const effects = []; let index = 0; let reads = 0; const writes = [];
  69. const fakeReact = { ...React, useCallback: fn => fn, useMemo: fn => fn(),
  70. createContext: () => ({ Provider: 'context-provider' }),
  71. useState: initial => { const i = index++; if (!(i in state)) state[i] = initial; return [state[i], value => { state[i] = value; }]; },
  72. useEffect: callback => effects.push(callback),
  73. };
  74. const document = { documentElement: { lang: 'en' } };
  75. const load = loader({ react: fakeReact }, { document, navigator: { language: 'zh-CN' }, localStorage: { getItem: () => { reads++; return expectedDefault === 'en' ? 'zh' : 'en'; }, setItem: (...args) => writes.push(args) } });
  76. const Provider = load('src/lib/i18n/LanguageContext.tsx').LanguageProvider;
  77. const element = Provider({ children: null, ...options });
  78. assert.equal(element.props.value.lang, expectedDefault);
  79. effects.forEach(fn => fn());
  80. assert.equal(reads > 0, detect);
  81. assert.equal(state[0], 'en', 'Homepage honors stored English; blog ignores stored Chinese');
  82. element.props.value.setLang('zh');
  83. assert.equal(state[0], 'zh');
  84. assert.deepEqual(writes[0], ['app_lang', 'zh']);
  85. assert.equal(document.documentElement.lang, options.updateDocumentLanguage === false ? 'en' : 'zh-CN');
  86. }
  87. providerCase({ initialLang: 'en', detectPreference: false, updateDocumentLanguage: false }, 'en', false);
  88. providerCase({}, 'zh', true);
  89. // Simulated shared-Navbar hooks cover mobile/auth branches without a browser or real session.
  90. for (const [logged, admin, open] of [[false, false, false], [false, false, true], [true, false, true], [true, true, true]]) {
  91. let index = 0; const states = [logged, admin, open]; const effects = []; const changes = []; let logoutCalls = 0; const events = [];
  92. 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) };
  93. const load = loader({ ...nextMocks, react: fakeReact,
  94. '@/lib/i18n/LanguageContext': { useLanguage: () => ({ t: key => key.split('.').pop(), lang: 'en', setLang: () => {} }) },
  95. '@/lib/auth': { isAdmin: () => admin, logout: () => { logoutCalls++; } },
  96. }, { localStorage: { getItem: () => logged ? 'test-session-marker' : null }, window: { addEventListener: (name, callback) => events.push([name, callback]), removeEventListener: () => {} } });
  97. const tree = load('src/components/Navbar.tsx').default({ showBlog: true, blogHref: '/blogs', navigationLanguageOnly: true });
  98. const nodes = [];
  99. function visit(node) { if (Array.isArray(node)) return node.forEach(visit); if (!node || typeof node !== 'object') return; nodes.push(node); visit(node.props?.children); }
  100. visit(tree);
  101. for (const href of ['/blogs', '/services', '/slots', logged ? '/dashboard' : '/login']) assert(nodes.some(n => n.props?.href === href));
  102. assert.equal(nodes.some(n => n.props?.href === '/admin'), logged && admin);
  103. assert.equal(nodes.some(n => n.props?.id === 'site-mobile-menu'), open);
  104. const toggle = nodes.find(n => n.props?.['aria-controls'] === 'site-mobile-menu');
  105. assert.equal(toggle.props['aria-expanded'], open); toggle.props.onClick();
  106. assert(changes.some(([i, value]) => i === 2 && value === !open));
  107. effects.forEach(fn => fn()); assert(events.some(([name]) => name === 'storage'));
  108. assert(changes.some(([i, value]) => i === 0 && value === logged));
  109. if (logged) { nodes.find(n => n.props?.title === 'logout').props.onClick(); assert.equal(logoutCalls, 1); assert(changes.some(([i, value]) => i === 2 && value === false)); }
  110. if (open) { nodes.find(n => n.props?.className?.includes('fixed inset-0')).props.onClick(); assert(changes.some(([i, value]) => i === 2 && value === false)); }
  111. }
  112. 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.');