10

I am using vue-i18n plugin for my Vue3(typescript) application. Below is my setup function in component code

Home.vue

import {useI18n} from 'vue-i18n'

setup() {
        const {t} = useI18n()
return {
        t
     }

}

Main.ts

import { createI18n } from 'vue-i18n'
import en from './assets/translations/english.json'
import dutch from './assets/translations/dutch.json'

// internationalization configurations
const i18n = createI18n({
    messages: {
        en: en,
        dutch: dutch
    },
    fallbackLocale: 'en',
    locale: 'en'
    
})
// Create app
const app = createApp(App)
app.use(store)
app.use(router)
app.use(i18n)

app.mount('#app')

Code works and compiles fine. But jest test cases fails for the component when it's mounting

Spec file

import { mount, VueWrapper } from '@vue/test-utils'
import Home from '@/views/Home.vue'
import Threat from '@/components/Threat.vue'

// Test case for Threats Component

let wrapper: VueWrapper<any>

beforeEach(() => {
  wrapper = mount(Home)
  // eslint-disable-next-line @typescript-eslint/no-empty-function
  jest.spyOn(console, 'warn').mockImplementation(() => { });
});

describe('Home.vue', () => {

  //child component 'Home' existance check
  it("Check Home component exists in Threats", () => {

    expect(wrapper.findComponent(Home).exists()).toBe(true)
  })

  // Threat level list existance check
  it("Check all 5 threat levels are listed", () => {
    expect(wrapper.findAll('.threat-level .level-wrapper label')).toHaveLength(5)
  })


})

Below is the error

Jest error log

Please help me to resolve this.

Purni
  • 297
  • 7
  • 19

2 Answers2

22

The vue-18n plugin should be installed on the wrapper during mount with the global.plugins option:

import { mount } from '@vue/test-utils'
import { createI18n } from 'vue-i18n'
import Home from '@/components/Home.vue'

describe('Home.vue', () => {
  it('i18n', () => {
    const i18n = createI18n({
      // vue-i18n options here ...
    })

    const wrapper = mount(Home, {
      global: {
        plugins: [i18n]
      }
    })

    expect(wrapper.vm.t).toBeTruthy()
  })
})

GitHub demo

tony19
  • 125,647
  • 18
  • 229
  • 307
1

You can also define the plugin globally in the setup/init file:

import { config } from '@vue/test-utils'
import { createI18n } from 'vue-i18n'
    
const i18n = createI18n({
  // vue-i18n options here ...
})
    
config.global.plugins = [i18n]
config.global.mocks.$t = (key) => key
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
Sayade
  • 57
  • 4