用开玩笑嘲笑i18n

时间:2019-11-09 11:42:35

标签: javascript typescript vue.js jestjs vue-i18n

我正在尝试在复杂的自定义monorepo上为Vue设置Jest单元测试,而i18n出现问题,因为我将其用于应用程序的翻译管理。

给出以下用于实例化i18n的代码:

import Vue from "vue"
import VueI18n from "vue-i18n"
import { getTranslations, addMissingKey, getLocaleFromBrowser, SUPPORTED_LOCALE } from "./api"
import { dateTimeFormats } from "./formats"

Vue.use(VueI18n)

export const defaultLocale = getLocaleFromBrowser()

const i18n = new VueI18n({
    locale: defaultLocale,
    dateTimeFormats,
    missing: (_locale: string, key: string) => {
        addMissingKey(key, false)
    },
    fallbackLocale: SUPPORTED_LOCALE.EN,
})
export default i18n

const loadTranslations = async (locale: SUPPORTED_LOCALE) => {
    i18n.mergeLocaleMessage(
        locale,
        await getTranslations(locale),
    )
}

export const changeLocale = async (locale: SUPPORTED_LOCALE) => {
    if (i18n.locale === locale) {
        return
    }
    await loadTranslations(locale)
    i18n.locale = locale
    document.getElementsByTagName("html")[0].lang = locale
}

并在执行测试时出现此错误:

 Test suite failed to run

    TypeError: Cannot read property 'use' of undefined

      14 |     locale: defaultLocale,
      15 |     dateTimeFormats,
    > 16 |     missing: (_locale: string, key: string) => {
         |               ^
      17 |         addMissingKey(key, false)
      18 |     },
      19 |     fallbackLocale: SUPPORTED_LOCALE.EN,

因此,由于未知原因,vue似乎未定义,我可能会遗漏某些东西,但是我该如何模拟它以避免发生此错误?

预先感谢

1 个答案:

答案 0 :(得分:0)

我相信您需要按如下所示将i18n添加到Vue

Vue.use(VueI18n);

const i18n = new VueI18n({
    locale: "en",
    messages
});

new Vue({
    i18n,  <==
    ...
    render: h => h(App)
}).$mount("#app");

在您的代码中,您可以在其中初始化主vue应用。