Greg Veres
Greg Veres

Reputation: 1900

how to mock v-t vue-i18n directive to return key during testing

I am using vue-i18n and the v-t directive. In my unit tests for my component, I would like to be able to test that the correct language key was supplied for the button (or other component).

I can mock out the $t function easily enough with:

config.mocks = {
  $t: (key) => key
};

but I can't do the same thing with v-t. This doesn't fill the key into the innerText or innerHTML of the element:

  localVue.directive('t', (el: HTMLElement, key: any) => {
    return key.value;
  });

Has anybody figured out how to mock the v-t directive to do something like this?

I am mounting (not shallowMount'ing) the component under test.

Upvotes: 0

Views: 1409

Answers (1)

Greg Veres
Greg Veres

Reputation: 1900

I figured out the answer. I was close, I had mistakenly assumed that the mock directive that I created on localVue had to return something, all it needed to do was set the innerText of the element that is passed to it. This is what the real v-t directive does, (actually, I think it sets innerHtml).

In the end, here is what to do:

  1. Define the mock directive like this:
localVue.directive('t', (el: HTMLElement, key: any) => {
  el.innerText = key.value;
});
  1. in your test, do the following (assuming you have a class on the div that contains the v-t directive)
  const div = wrapper.find('.divclass');
  expect(div.element.innerText).toBe('key');

And for completeness, lets assume your vue component looks like this:

<template>
  <div v-t='label' v-if="label" class="divclass"></div>
</template>

<script lang="ts">

import Vue from 'vue'
export default Vue.extend({
  inheritAttrs: false,
  name: 'MyLabelDiv',
  props: ['label']
})
</script>

Here the component takes a prop called label that is assumed to be a language key. If the label prop is set, then the div exists and will contain the language string identified by key.

Upvotes: 2

Related Questions