首页 > 解决方案 > 如何对使用 nuxt-i18n 的 Vue.js 组件进行单元测试

问题描述

如果我尝试运行下面的东西(使用yarn run jest),我得到TypeError: _vm.$t is not a function,因为SearchField正在使用翻译("$t('search')")。

import { mount } from "@vue/test-utils";
import SearchField from "@/components/ui/SearchField";

describe("SearchField", () => {
  const wrapper = mount(SearchField);

  it("renders correctly", () => {
    expect(wrapper.element).toMatchSnapshot();
  });
});

如果我在开头添加以下三行,则会得到TypeError: Cannot read property '_t' of undefined

import Vue from "vue";
import VueI18n from "vue-i18n";
Vue.use(VueI18n);

标签: vue.jsjestjsnuxt.jsnuxt-i18n

解决方案


nuxt-i18n 是一个外部库,而不是您自己的代码,因此测试良好实践要求我们仅模拟翻译库及其所需的功能($t在本例中)。

以下代码应该可以解决您的问题:

describe("SearchField", () => {
  const wrapper = mount(SearchField);

  it("renders correctly", () => {
    mocks: {
      $t: (msg) => msg
    }
    expect(wrapper.element).toMatchSnapshot();
  });
});

可以在此处找到有关此方法的更多信息。


推荐阅读