intlify / vue-i18n-composable

Composition API for vue-i18n in Vue 2.x
MIT License
44 stars 10 forks source link

unit testing #2

Closed danieleades closed 3 years ago

danieleades commented 4 years ago

what's the correct approach for unit testing using this library?

given this component-

<template>
    <div>
                {{ t("some.translation") }}
    </div>
</template>
import { defineComponent } from "@vue/composition-api";
import { useI18n } from "vue-i18n-composable";

export default defineComponent({
    setup() {
        const { t } = useI18n();
        return { t };
    },
});

i get an error when i shallow-mount this in a unit test

import "@/plugins/composition-api";
import { shallowMount } from "@vue/test-utils";
import Component from "@/views/Component.vue";

describe("Component", () => {
    it("can be mounted", () => {
        expect(() => {
            shallowMount(Component);
        }).not.toThrow();
    });
});

at the top of a long error output i see [Vue warn]: Error in data(): "Error: vue-i18n not initialized"

how should vue-i18n be initialised for this unit test?

antfu commented 4 years ago

Which test framework you are using? If you are using Jest you can check out https://jestjs.io/docs/en/setup-teardown

axe-me commented 3 years ago

I got similar trouble with my unit tests. The createI18n function configures the global Vue, but in the unit test, I need to config localVue. Is that possible to inject vue instance to the function as a second optional param?

export function createI18n(options?: VueI18n.I18nOptions, vue: VueConstructor = Vue) {
  vue.use(VueI18n)
  i18nInstance = new VueI18n(options)

  return i18nInstance
}

like this. I can create a PR if you think this is acceptable.

antfu commented 3 years ago

@kazupon I think @axe-me's solution is quite reasonable for testing, do you think we can have it? and how could we align this with vue-i18n-next?

kazupon commented 3 years ago

@antfu Yeah! I think it's reasonable solution for testing! we don't need to align at vue-i18n-next, because this solution for Vue 2.x and vue-i18n-composable only. In Vue 3, app instance generated by createApp is the local base, and is no longer the global base.

kazupon commented 3 years ago

I've just published v0.2.0 https://www.npmjs.com/package/vue-i18n-composable