Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock/stub vue-i18n?

I have started to replace Jest with Vitest for my unit test library in my Vue 3 App.

I am trying to write unit test for a component that uses the vue-i18n library to translate text within it but when I try to mount this component in my test file, it fails with the error:

ReferenceError: t is not defined

What is the proper way to stub/mock t from import { useI18n } from 'vue-i18n' when writing tests using the vitest library?

Note since upgrading from Vue2 to Vue3 this does not work:

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

Here is a list of some notable package versions:

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

Thanks!

like image 531
Mac Avatar asked Nov 16 '25 03:11

Mac


1 Answers

I suppose you want to mock this globally, no need to put same code in every test suite.

// 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
};
like image 181
Luckylooke Avatar answered Nov 18 '25 16:11

Luckylooke