check-blog-nav.cjs 6.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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 BlogNavbar = loadSSR('src/components/blog/BlogNavbar.tsx').default;
  35. const html = renderToStaticMarkup(React.createElement(BlogNavbar, { blogHref: '/blogs' }));
  36. for (const text of ['Services', 'Slot Check', 'Visa guides', 'Login / Sign up']) assert(html.includes(text), `Missing shared menu item: ${text}`);
  37. for (const href of ['/', '/blogs', '/services', '/slots', '/login']) assert(html.includes(`href="${href}"`));
  38. assert(html.includes('lang="en"') && html.includes('aria-expanded="false"'));
  39. assert(html.includes('aria-label="STRATA home"'));
  40. assert(html.includes('aria-label="ZH / 中文: Switch navigation language'), 'Accessible language-control name must include its visible target');
  41. assert(html.includes('Switch navigation language (article language stays unchanged)'));
  42. assert(!html.includes('服务工单库') && !html.includes('nav.services'), 'Blog navigation must SSR in English');
  43. // Simulated provider hooks test browser-preference isolation and document-language ownership.
  44. function providerCase(options, expectedDefault, detect) {
  45. const state = []; const effects = []; let index = 0; let reads = 0; const writes = [];
  46. const fakeReact = { ...React,
  47. createContext: () => ({ Provider: 'context-provider' }),
  48. useState: initial => { const i = index++; if (!(i in state)) state[i] = initial; return [state[i], value => { state[i] = value; }]; },
  49. useEffect: callback => effects.push(callback),
  50. };
  51. const document = { documentElement: { lang: 'en' } };
  52. const load = loader({ react: fakeReact }, { document, navigator: { language: 'zh-CN' }, localStorage: { getItem: () => { reads++; return expectedDefault === 'en' ? 'zh' : 'en'; }, setItem: (...args) => writes.push(args) } });
  53. const Provider = load('src/lib/i18n/LanguageContext.tsx').LanguageProvider;
  54. const element = Provider({ children: null, ...options });
  55. assert.equal(element.props.value.lang, expectedDefault);
  56. effects.forEach(fn => fn());
  57. assert.equal(reads > 0, detect);
  58. assert.equal(state[0], 'en', 'Homepage honors stored English; blog ignores stored Chinese');
  59. element.props.value.setLang('zh');
  60. assert.equal(state[0], 'zh');
  61. assert.deepEqual(writes[0], ['app_lang', 'zh']);
  62. assert.equal(document.documentElement.lang, options.updateDocumentLanguage === false ? 'en' : 'zh-CN');
  63. }
  64. providerCase({ initialLang: 'en', detectPreference: false, updateDocumentLanguage: false }, 'en', false);
  65. providerCase({}, 'zh', true);
  66. // Simulated shared-Navbar hooks cover mobile/auth branches without a browser or real session.
  67. for (const [logged, admin, open] of [[false, false, false], [false, false, true], [true, false, true], [true, true, true]]) {
  68. let index = 0; const states = [logged, admin, open]; const effects = []; const changes = []; let logoutCalls = 0; const events = [];
  69. const fakeReact = { ...React, useState: () => { const i = index++; return [states[i], value => changes.push([i, value])]; }, useEffect: callback => effects.push(callback) };
  70. const load = loader({ ...nextMocks, react: fakeReact,
  71. '@/lib/i18n/LanguageContext': { useLanguage: () => ({ t: key => key.split('.').pop(), lang: 'en', setLang: () => {} }) },
  72. '@/lib/auth': { isAdmin: () => admin, logout: () => { logoutCalls++; } },
  73. }, { localStorage: { getItem: () => logged ? 'test-session-marker' : null }, window: { addEventListener: (name, callback) => events.push([name, callback]), removeEventListener: () => {} } });
  74. const tree = load('src/components/Navbar.tsx').default({ showBlog: true, blogHref: '/blogs', navigationLanguageOnly: true });
  75. const nodes = [];
  76. function visit(node) { if (Array.isArray(node)) return node.forEach(visit); if (!node || typeof node !== 'object') return; nodes.push(node); visit(node.props?.children); }
  77. visit(tree);
  78. for (const href of ['/blogs', '/services', '/slots', logged ? '/dashboard' : '/login']) assert(nodes.some(n => n.props?.href === href));
  79. assert.equal(nodes.some(n => n.props?.href === '/admin'), logged && admin);
  80. assert.equal(nodes.some(n => n.props?.id === 'site-mobile-menu'), open);
  81. const toggle = nodes.find(n => n.props?.['aria-label'] === 'Toggle Menu');
  82. assert.equal(toggle.props['aria-expanded'], open); toggle.props.onClick();
  83. assert(changes.some(([i, value]) => i === 2 && value === !open));
  84. effects[0](); assert(events.some(([name]) => name === 'storage'));
  85. assert(changes.some(([i, value]) => i === 0 && value === logged));
  86. if (logged) { nodes.find(n => n.props?.title === 'logout').props.onClick(); assert.equal(logoutCalls, 1); assert(changes.some(([i, value]) => i === 2 && value === false)); }
  87. if (open) { nodes.find(n => n.props?.className?.includes('fixed inset-0')).props.onClick(); assert(changes.some(([i, value]) => i === 2 && value === false)); }
  88. }
  89. console.log('PASS: shared navbar SSR links/actions and English labels; 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.');