使用Vue-I18 N测试Cypress组件

qhhrdooz  于 2023-04-07  发布在  Vue.js
关注(0)|答案(1)|浏览(311)

我尝试在Vue应用中使用Cypress进行组件测试。我使用vue-i18 n库为应用提供本地化。当尝试测试我的加载微调器组件的渲染时,我从vue-i18 n库中获得以下错误:

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)

在此之前,我从Pinia得到一个错误。我通过将以下内容添加到cypress/support/component.ts来解决这个问题:

import { createPinia, setActivePinia } from 'pinia';

setActivePinia(
  createPinia()
);

我的LoadingSpinner组件代码如下:

<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>

测试代码:

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 };
});

我发现this github release意味着我需要将vue-i18 n作为插件添加到mount()调用中,但我不知道如何做到这一点。有人知道解决方案吗?

vu8f3i0k

vu8f3i0k1#

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)
})

相关问题