Files
monkey-ai-web/test/unit/i18n-render-regressions.test.js
zhanjunhao 2aa9d73325 chore(repo): 移除重复版权文件头并纳入共享单测
集中保留原版权声明,移除文件头检查和全局测试忽略规则。验证:全量单测、受影响用例复测及静态检查通过。
2026-11-20 11:23:49 +08:00

167 lines
5.0 KiB
JavaScript

import assert from 'node:assert/strict';
import { readFile } from 'node:fs/promises';
import test from 'node:test';
import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
import { Link } from 'react-router-dom';
import { StaticRouter } from 'react-router-dom/server.js';
import { Trans } from 'react-i18next';
import { createInstance } from 'i18next';
import { parse } from '@babel/parser';
import { transformWithEsbuild } from 'vite';
import { loadFrontendModule } from './frontend-module.js';
const filename = new URL('../../src/helpers/render.jsx', import.meta.url);
const source = await readFile(filename, 'utf8');
const ast = parse(source, { sourceType: 'module', plugins: ['jsx'] });
const i18n = createInstance();
await i18n.init({
lng: 'en',
fallbackLng: 'zh',
keySeparator: false,
nsSeparator: false,
interpolation: { escapeValue: false },
resources: Object.fromEntries(
await Promise.all(
['zh', 'en'].map(async (code) => [
code,
JSON.parse(
await readFile(
new URL(`../../src/i18n/locales/${code}.json`, import.meta.url),
'utf8',
),
),
]),
),
),
});
const mocks = Object.fromEntries(
ast.program.body
.filter((node) => node.type === 'ImportDeclaration')
.map((node) => [
node.source.value,
Object.fromEntries(
node.specifiers.map((specifier) => [
specifier.imported?.name || 'default',
specifier.local.name,
]),
),
]),
);
mocks.react = React;
mocks.i18next = { __esModule: true, default: i18n };
const { renderModelPriceSimple } = await loadFrontendModule(filename, mocks);
test('price descriptions interpolate each segment before joining in both languages', async () => {
for (const language of ['zh', 'en']) {
await i18n.changeLanguage(language);
const text = renderModelPriceSimple(
2,
-1,
3,
4,
10,
0.5,
20,
1.25,
30,
1.5,
40,
2.5,
// weiyuan 76d4f4a4c 新增:未分档缓存创建 tokens / 倍率
50,
0.6,
true,
0.75,
true,
);
for (const value of ['2', '0.5', '1.5', '2.5', '0.6', '0.75', '4']) {
assert.ok(text.includes(value), text);
}
assert.ok(text.includes(i18n.t('专属倍率')), text);
assert.ok(text.endsWith(i18n.t('系统提示覆盖')), text);
assert.ok(!text.includes('1.25'), 'split cache creation takes precedence');
assert.doesNotMatch(text, /\{\{|\}\}/);
if (language === 'en') assert.match(text, /^Model: 2 \* /);
}
});
test('legacy cache creation is included only when cache tokens are present', async () => {
await i18n.changeLanguage('zh');
const plain = renderModelPriceSimple(2, -1, 3);
assert.equal(plain, '模型: 2 * 分组倍率: 3');
const legacy = renderModelPriceSimple(2, -1, 3, undefined, 0, 1, 10, 1.25);
assert.equal(legacy, '模型: 2 * 缓存创建: 1.25 * 分组倍率: 3');
});
test('translated sentences reorder linked components and keep navigation props', async () => {
const key = '在<part0>「密钥管理」</part0>页面找到刚创建的密钥';
const local = createInstance();
await local.init({
lng: 'en',
resources: {
en: {
translation: {
[key]: 'Find the new key on <part0>Key Management</part0>.',
},
},
zh: { translation: { [key]: key } },
},
});
const tutorial = await readFile(
new URL('../../src/pages/Tutorial/index.jsx', import.meta.url),
'utf8',
);
let sentence;
const findSentence = (node) => {
if (!node || typeof node !== 'object') return;
if (
node.type === 'JSXElement' &&
node.openingElement.name.name === 'Trans' &&
node.openingElement.attributes.some(
(attr) => attr.name?.name === 'i18nKey' && attr.value?.value === key,
)
) {
sentence = tutorial.slice(node.start, node.end);
return;
}
for (const value of Object.values(node)) {
if (Array.isArray(value)) value.forEach(findSentence);
else if (value && typeof value === 'object') findSentence(value);
}
};
findSentence(parse(tutorial, { sourceType: 'module', plugins: ['jsx'] }));
assert.ok(sentence, 'use the actual tutorial sentence and its Link props');
const { code } = await transformWithEsbuild(
`const element = (${sentence});`,
'sentence.jsx',
{ loader: 'jsx' },
);
const element = new Function(
'React',
'Trans',
'Link',
't',
`${code}; return element;`,
);
const render = () =>
renderToStaticMarkup(
React.createElement(
StaticRouter,
{ location: '/' },
element(
React,
(props) => React.createElement(Trans, { ...props, i18n: local }),
Link,
local.t.bind(local),
),
),
);
const english = render();
assert.match(english, /^Find the new key on /);
assert.match(english, /href="\/user-center\/key-management"/);
assert.match(english, /class="tutorial-link"/);
await local.changeLanguage('zh');
assert.match(render(), /^在<a/);
});