0

Though I have a working solution using the global object I'd love to avoid injection. Is there a way to use mocking to achieve this?

This is only about the mocking so the code is stripped down to only show this step.

//myComponent.vue
<template>
  <div>{{$t('some.label')}}</div>
</template>

<script lang="ts">
import {defineComponent} from "vue"
export default defineComponent({
  inject: ['$t'],
  setup(){},
})
</script>

This one works.

//test
import myComponent from '../myComponent'
import { createI18n } from 'vue-i18n'
const i18n = createI18n({locale: 'en'})
const t = i18n.global.tm
const globalProvide = {
    global: {
        provide: {
            $t: t
        }
    }
}
mount(myComponent, globalProvide)

This one doesen't. this.$t is not a function.

//test
import myComponent from '../myComponent'

mount(myComponent, {
  mocks: {
    $t: (msg) => { msg }
  }
})
Fody
  • 23,754
  • 3
  • 20
  • 37
Hexodus
  • 12,361
  • 6
  • 53
  • 72

1 Answers1

2

It looks like you might've been trying the v1 syntax of Test Utils for mocks, but that has moved in v2.

To mock $t, use the global.mocks mounting option:

mount(myComponent, {
  global: {
    mocks: {
      $t: (msg) => { msg }
    }
  }
})
tony19
  • 125,647
  • 18
  • 229
  • 307