0

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.

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.