【问题标题】:Best way to mock/stub vue-i18n translations in a vue3 component when using Vitest使用 Vitest 时在 vue3 组件中模拟/存根 vue-i18n 翻译的最佳方法
【发布时间】:2022-08-20 14:38:36
【问题描述】:

我已经开始用 Vitest 替换 Jest,用于我的 Vue 3 应用程序中的单元测试库。

我正在尝试为使用vue-i18n 库在其中翻译文本的组件编写单元测试,但是当我尝试将此组件安装到我的测试文件中时,它失败并出现错误:

ReferenceError: t 未定义

使用 vitest 库编写测试时,从import { useI18n } from \'vue-i18n\' 存根/模拟t 的正确方法是什么?

请注意,因为从 Vue2 升级到 Vue3 这不起作用:

const wrapper = shallowMount(MyComponent, {
  global: {
    mocks: {
      $t: () => {}
    }
  }
})

以下是一些值得注意的软件包版本的列表:

\"vue\": \"^3.2.31\",
\"vue-i18n\": \"^9.2.0-beta.14\",
\"vite\": \"^2.9.0\",
\"vitest\": \"^0.10.2\"

谢谢!

    标签: unit-testing vuejs3 vue-i18n vitest


    【解决方案1】:
    import { createI18n } from 'vue-i18n';
    
    describe('xxx', () => {
       it('yyy', () => {
          const i18n = createI18n({
             messages: {
                gb: {},
                nl: {},
                ...
             }
          });
          
          const wrapper = mount(YourComponent, {
             global: {
                plugins: [i18n]
             }
          });
       }
    })
    

    【讨论】:

      【解决方案2】:

      我想你想在全球范围内模拟这个,不需要在每个测试套件中放置相同的代码。

      // vitest.config.ts
      import { mergeConfig } from 'vite';
      import { defineConfig } from 'vitest/config';
      import viteConfig from './vite.config';
      
      export default defineConfig(
          mergeConfig(viteConfig, { // extending app vite config
              test: {
                  setupFiles: ['tests/unit.setup.ts'],
                  environment: 'jsdom',
              }
          })
      );
      
      // tests/unit.setup.ts
      import { config } from "@vue/test-utils"
      
      config.global.mocks = {
        $t: tKey => tKey; // just return translation key
      };
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-03
        • 2020-05-06
        • 2021-03-05
        • 2021-04-26
        • 2020-12-20
        • 1970-01-01
        • 2019-06-14
        • 1970-01-01
        相关资源
        最近更新 更多