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!
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
};
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With