check-blog-nav.cjs 8.1 KB

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