Jest错误“语法错误:使用Vue 3的vue-i18 n插件时,需要安装'app.use' function”

d6kp6zgx  于 2022-12-08  发布在  Jest
关注(0)|答案(2)|浏览(466)

我正在为我的Vue 3(typescript)应用程序使用vue-i18 n插件。下面是我的组件代码中的设置函数

首页.版本

import {useI18n} from 'vue-i18n'

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

}

主文件.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')

代码工作正常,编译良好,但是组件在挂载时jest测试用例失败

等级库文件

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)
  })

})

以下是错误

请帮我解决这个问题。

ykejflvf

ykejflvf1#

vue-18n插件应该在挂载期间使用global.plugins选项安装在 Package 器上:

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

nhaq1z21

nhaq1z212#

您还可以在setup/init文件中全局定义插件:

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

相关问题