1

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>
Theiaz
  • 568
  • 6
  • 24
  • Please, provide the code that this warning refers to. It says about instance property. It's not directly tied to vue-i18n mock. What does "still getting" mean? Was there a warning before a mock? – Estus Flask Mar 14 '23 at 12:58
  • I've provided my config and an example component. My test does simply mount the component `mount(Foo);` "Still getting" means, that in my opinion the code is fine (productive code works as expected, no warnings), however the test does still print this warning. – Theiaz Mar 14 '23 at 15:15
  • I see no problem with this code. In this case it's only possible for this comp to cause this warning if setup function failed to execute and return { t }, e.g. useI18n is not a function. If that's the case there should be errors in console. – Estus Flask Mar 14 '23 at 15:48
  • Okay I've figured out my problem. In some tests I've called `jest.resetAllMocks()` which resets the globally applied mock of vue-i18n. After changing it to `jest.clearAllMocks()` its working again! – Theiaz Mar 15 '23 at 08:42
  • Makes sense. Reset mocks is really a footgun. – Estus Flask Mar 15 '23 at 11:01

0 Answers0