包括一个本地化库,并且我的组件中有一个日期对象,看起来像这样:
getDate = () => {
const { t } = this.props;
return new Date().toLocaleString(t('locale.name'), {
weekday: "long",
month: "long",
day: "numeric",
});
};
[当我尝试运行测试时,出现错误:
RangeError: Invalid language tag: language.name at Date.toLocaleString ()
15 | getDate = () => {
16 | const { t } = this.props;
> 17 | return new Date().toLocaleString(t('language.name'), {
| ^
18 | weekday: "long",
19 | month: "long",
20 | day: "numeric",
因此它无法识别i18n语言环境。这与我嘲笑i18n的方式有关吗?
我当前的设置:
react-i18next.ts:
jest.mock('i18next', () => ({
use: () => {
return {
init: () => { }
};
},
t: k => k
}));
我的jest.config:
module.exports = {
verbose: true,
roots: ["<rootDir>"],
testRegex: "/__tests__/.*\\.(test|spec)\\.tsx?",
transform: {
"^.+\\.tsx?$": "ts-jest",
},
moduleNameMapper: {
"react-i18next": "<rootDir>/__tests__/__mock__/react-i18next.ts"
},
};
i18n.ts
import i18n from "i18next";
import {initReactI18next} from "react-i18next";
import english from "./locales/en/common.json";
import french from "./locales/fr/common.json";
i18n.use(initReactI18next).init({
lng: 'en',
resources: {
fr: {
translation: french,
},
en: {
translation: english,
},
},
interpolation: {
escapeValue: false,
},
fallbackLng: ["en"]
});
export default i18n;
您对t的模拟使它自己返回键,因此,toLocaleString
获得language.name作为一种语言,并抛出“无效的语言标签”。
我使用本地化日期格式的方法是使用formatting
方法按地区设置日期格式。
formatting
// i18next.config.js
...
{
interpolation: {
format: (value, format, lng) => {
if (value instanceof Date) {
const cloneDate = new Date(value);
return cloneDate.toLocaleString(lng, mapFormatToLocale[format]);
}
return value;
};
}
}
...
const mapFormatToLocale = {
YYYYmmdd: {
weekday: 'long',
month: 'long',
day: 'numeric',
},
};
// locale.en.json
{
"MY_DATE": "My Date {{date, YYYYmmdd}}"
}
此方法最酷的部分是您在转换json文件中定义了日期格式样式,这意味着您可以根据需要按每种语言进行更改。
此方法可以反转语言环境和日期之间的deps,并且可以与您的模拟一起使用,因为您的模拟只会返回翻译键。