user14131782
user14131782

Reputation: 1068

Cypress component testing with Vue-I18N

I am trying to use Cypress for component testing in my Vue app. I am using the vue-i18n library to provide localisation for the app. When attempting to test the rendering of my loading spinner component, I am getting the following error from the vue-i18n library:

SyntaxError: Need to install with `app.use` function
at createCompileError (http://localhost:5173/__cypress/src/node_modules/.vite/deps/vue-i18n.js?v=64756eb2:183:17)
at createI18nError (http://localhost:5173/__cypress/src/node_modules/.vite/deps/vue-i18n.js?v=64756eb2:2625:10)
at useI18n (http://localhost:5173/__cypress/src/node_modules/.vite/deps/vue-i18n.js?v=64756eb2:4231:11)

Previously to this, I was getting an error from Pinia. I resolved this by adding the following to cypress/support/component.ts:

import { createPinia, setActivePinia } from 'pinia';

setActivePinia(
  createPinia()
);

My LoadingSpinner component code is as follows:

<script setup lang="ts">
import { computed } from "@vue/reactivity";
import { useLocaleStore } from "@/stores/locale";

//props

const { i18n } = useLocaleStore();
</script>

<template>
  <div class="d-flex justify-content-center m-5">
    <div
      class="spinner-border text-primary"
      :style="{ width, height }"
      role="status"
    >
      <span class="visually-hidden">{{ i18n.t("loading") }}</span>
    </div>
  </div>
</template>

And the test code:

import LoadingSpinner from "../../src/components/ui/LoadingSpinner.vue";

describe("LoadingSpinner", () => {
  it("renders", () => {
    cy.mount(LoadingSpinner);
  });
});

/stores/locale:

import { computed } from "vue";
import { defineStore } from "pinia";
import { useI18n } from "vue-i18n";

export const useLocaleStore = defineStore("locale", () => {
  const i18n = useI18n({
    useScope: "global",
    inheritLocale: true,
  });

  const currentLocale = computed(() => i18n.locale);
  const locales = computed(() => i18n.availableLocales);

  return { i18n, currentLocale, locales };
});

I found this github release that implies I need to add vue-i18n as a plugin to the mount() call, but I can't work out how to do it. Does anyone know a solution?

Upvotes: 1

Views: 2040

Answers (1)

Orbis
Orbis

Reputation: 475

Cypress.Commands.add('mount', (component, options = {}) => {
  // Setup options object
  options.global = options.global || {}
  options.global.stubs = options.global.stubs || {}
  options.global.stubs.transition = false
  options.global.components = options.global.components || {}
  options.global.plugins = options.global.plugins || []

  // Use store passed in from options, or initialize a new one
  const {/* store = getStore(), */ ...mountOptions} = options

  // Add plugins here
  options.global.plugins.push({
    install(app) {
      app.use(i18n)
    },
  })

  return mount(component, mountOptions)
})

Upvotes: 0

Related Questions