Jest error "SyntaxError: Need to install with `app.use` function" when using vue-i18n plugin for Vue3
Asked Answered
P

2

14

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.

Preciousprecipice answered 24/2, 2021 at 9:48 Comment(0)
B
26

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

Backpedal answered 25/2, 2021 at 16:50 Comment(0)
W
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
Western answered 23/10, 2022 at 10:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.