Search code examples
typescriptvuejs3vue-i18nvitest

Vitest - TypeError: _ctx.$t is not a function


I have a vue 3 project with typescript. I used vue-i18n for localization and for test, I use vitest. When I want to render components in test that have i18n, got this error:

How can I fix it?

TypeError: _ctx.$t is not a function
 ❯ Proxy._sfc_render src/components/loader/AppLoader.vue:11:52
      9|     </div>
     10|     <div v-else-if="isEmpty">
     11|       <span class="text-gray-500 text-lg block">{{ $t('message.empty') }}</span>
       |                                                    ^
     12|     </div>
     13|   </div

Solution

  • I had the same issue. I am new to vitest and vue/test-utils.

    I found a solution, here: https://blog.albert.do/quasar-unit-test-with-vitest-i18n-and-the-t-method/

    My issue goes away if I mount my component like so:

    const wrapper = mount(MyComponent, {
      global: { 
        mocks: {
          $t: (msg) => msg 
        }
      }
    });
    

    This installs a little function $t which just returns the message it gets, untranslated.

    With that, testing translation is impossible, but testing if literal translation strings are present, is handy.