简体   繁体   中英

Mock i18n for vue with jest

I'm trying to setup jest unit test for Vue on a complex custom monorepo and I have an issue with i18n with I use for translation management on my app.

Given the following code for instantiating 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
}

and having this error on test execution:

 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,

So it seems that vue is undefined for an unknown reason I might be missing something but how can I mock this to avoid this error?

Thanks in advance

I believe you'll need to add i18n to Vue as below

Vue.use(VueI18n);

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

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

in your code where you initialize the main vue app.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM