【问题标题】:Mock i18n for vue with jest用 jest 模拟 vue 的 i18n
【发布时间】:2020-03-05 19:35:05
【问题描述】:

我正在尝试在一个复杂的自定义 monorepo 上为 Vue 设置笑话单元测试,我在使用 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 似乎由于未知原因未定义,我可能会遗漏一些东西,但我该如何模拟它以避免此错误?

提前致谢

【问题讨论】:

  • 嗨!你找到解决办法了吗?

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


【解决方案1】:

我相信你需要将 i18n 添加到 Vue 中,如下所示

Vue.use(VueI18n);

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

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

在您初始化主 vue 应用程序的代码中。

【讨论】:

    猜你喜欢
    • 2019-06-10
    • 2019-10-09
    • 1970-01-01
    • 2019-11-22
    • 2018-09-01
    • 2020-03-07
    • 2021-03-20
    • 2019-03-05
    • 1970-01-01
    相关资源
    最近更新 更多