Solution:
Add this to your jest init file. It only partially mocks the module. If you need to use jest.resetAllMocks()
this may lead to an error, because you'll also reset this mock. Workaround could be to use it per test file, instead of using it globally.
// jest.init.js
import { createI18n, useI18n } from "vue-i18n";
jest.mock("vue-i18n", () => {
return {
...jest.requireActual("vue-i18n");
useI18n: jest.fn().mockReturnValue({
t: (key) => key,
}),
};
});
I'm using jest, vue-test-utils and vue3 (composition api). I want to globally mock the vue-i18n functions like t('key')
. With options-api i just need to write
// jest.init.js
import { config } from "@vue/test-utils";
config.global.mocks = {
$t: (text) => text
}
How to achieve the same behaviour with composition api and const { t } = useI18n();
?
I tried the following:
// jest.init.js
import { createI18n, useI18n } from "vue-i18n";
jest.mock("vue-i18n", () => {
return {
...jest.requireActual("vue-i18n");
useI18n: jest.fn().mockReturnValue({
t: (key) => key,
}),
};
});
However, I'm still getting this console warning after running my test run:
console.warn [Vue warn]: Property "t" was accessed during render but is not defined on instance.
I've also seen this post but it doenst help me to fix the console warning
Edit: Here is my config and a code-snippet:
const i18n = createI18n({
legacy: false,
messages, // set locale messages
// other options
});
export { i18n };
<template>
<p>{{ t("foo.bar.route.description") }}</p>
</template>
<script>
import { useI18n } from "vue-i18n";
export default {
name: "Foo",
setup() {
const { t } = useI18n();
return {
t,
};
},
};
</script>